如何在带有多个变量的ggplot图中绘制图例?

时间:2020-10-16 12:25:35

标签: r ggplot2

我有以下代码

ggplot(df.np.prod.cons.daily[df.np.prod.cons.daily$Region=="EE", ]) + 
      geom_line(aes(x = Date, y = Production),  color="red", size=1) + 
      geom_line(aes(x = Date, y = Consumption), color="blue", size=1)+
      geom_bar(aes(x = Date, y = prodVScons), stat = 'identity', position = 'dodge', color="gray")+
      theme_economist()+
      guides(fill = guide_legend(override.aes = list(colour = NULL)))

我的图在看:
enter image description here

如何添加图例,以说明哪种颜色对应于哪个变量? (如果您帮我描绘一种颜色的条形图,那将是很好的,当它是正数时,值是正的,而另一种颜色是正色的;然后在图例中告诉变量prodVScons是2种颜色)

1 个答案:

答案 0 :(得分:0)

也许这就是您想要的。

  1. 在@AllanCameron和我自己在color中移动aes并添加scale_color_manual之后,我将添加一个图例。
  2. 要为负条和正条获得不同的颜色,请使颜色取决于该值。
  3. 要获得填充条,我还使用了fill aes和scale_fill_manual
  4. 最后,我决定将一行用作图例键符号,并将所有三个几何的key_glyph设置为“ path"

使用一些随机示例数据尝试以下操作:

library(ggplot2)
library(ggthemes)

df.np.prod.cons.daily <- data.frame(
  Region = "EE",
  Date = 1:100,
  Production = runif(100, 20000, 30000),
  Consumption = runif(100, 10000, 20000),
  prodVScons = runif(100, -10000, 10000)
)

ggplot(df.np.prod.cons.daily[df.np.prod.cons.daily$Region=="EE", ]) + 
  geom_line(aes(x = Date, y = Production,  color="red"), size=1, key_glyph = "path") + 
  geom_line(aes(x = Date, y = Consumption, color="blue"), size=1, key_glyph = "path")+
  geom_bar(aes(x = Date, y = prodVScons, 
               color = ifelse(prodVScons < 0, "grey40", "grey80"),
               fill = ifelse(prodVScons < 0, "grey40", "grey80")), 
           stat = 'identity', position = 'dodge', key_glyph = "path")+
  theme_economist()+
  scale_color_manual(values = c(red = "red", blue = "blue", grey40 = "grey40", grey80 = "grey80"))+
  scale_fill_manual(values = c(red = "red", blue = "blue", grey40 = "grey40", grey80 = "grey80")) +
  guides(fill = FALSE)