条件形状/颜色图

时间:2018-12-07 18:22:08

标签: r ggplot2 plot

我有一个看起来像这样的数据框

categories <- c('a', 'b', 'c', 'd', 'e')
trends <- c(.20, -.05, 0, .1, 0)

df <- as.data.frame(categories, trends)

我正在尝试创建一个图,该图具有正向趋势的绿色三角形,负向趋势的红色三角形和零趋势的黑色正方形。

这是我的尝试,但是颜色和指南不正确。

ggplot(
  df %>%
    mutate(color_index = ifelse(trends > 0, "green", 
                         ifelse(trends < 0, "red", "black")),
           shape_id = ifelse(trends > 0, 24, 
                      ifelse(trends < 0, 25, 22))),

  aes(x = categories, y = trends, fill = color_index)) +

  # up/down arrow points
  geom_point(aes(shape = shape_id), size = 7) +
  scale_shape_identity() +
  geom_text(aes(label=trends*100), size = 4, nudge_y=-0.01, check_overlap = TRUE) 

enter image description here

1 个答案:

答案 0 :(得分:3)

scale_fill_identity添加到情节中

ggplot(df1, aes(x = categories, y = trends, fill = color_index)) +
  # up/down arrow points
  geom_point(aes(shape = shape_id), size = 7) +
  scale_shape_identity() +
  scale_fill_identity() +
  geom_text(aes(label=trends*100), size = 4, nudge_y=-0.01, check_overlap = TRUE) 

enter image description here

数据

categories <- c('a', 'b', 'c', 'd', 'e')
trends <- c(.20, -.05, 0, .1, 0)

df <- data.frame(categories, trends)
df1 <- df %>%
  mutate(color_index = ifelse(trends > 0, "green", 
                              ifelse(trends < 0, "red", "black")),
         shape_id = ifelse(trends > 0, 24, 
                           ifelse(trends < 0, 25, 22)))
相关问题