简体   繁体   English

如何使用多个变量在 ggplot 图中绘制图例?

[英]How plot legend in ggplot graph with several variables?

I have the following code我有以下代码

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)))

My graph is looking:我的图表正在寻找:
在此处输入图片说明

How can I add the legend, which tells which color corresponds to which variable?如何添加图例,说明哪种颜色对应于哪个变量? (It will be also great if you help me to depict barplot as in one colour went the values are positive and different colour when it is positive- and then in the legend tell that variable prodVScons is with 2 colours) (如果你能帮我描绘条形图,因为当它是正时,值是正的,而不同的颜色 - 然后在图例中告诉变量 prodVScons 有两种颜色,这也很棒)

Maybe this is what your are looking for.也许这就是你正在寻找的。

  1. Following the comments by @AllanCameron and myself moving color inside aes and adding scale_color_manual will add a legend.按照@AllanCameron 的评论和我自己在aes移动color并添加scale_color_manual将添加一个图例。
  2. To get different colors for negative and positive bars make the color conditional on the value.要获得负条和正条的不同颜色,请根据值设置颜色。
  3. To get filled bars I also make use of the fill aes and scale_fill_manual为了获得填充条,我还使用了fill aes 和scale_fill_manual
  4. Finally, I decided for a line as legend key symbol and set the key_glyph to " path" for all three geoms最后,我决定了线像传说中的关键标志,并设置key_glyph以“ path"为所有三个geoms

Using some random example data try this:使用一些随机示例数据试试这个:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM