简体   繁体   中英

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)

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.
  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
  4. Finally, I decided for a line as legend key symbol and set the key_glyph to " path" for all three 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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