[英]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.也许这就是你正在寻找的。
color
inside aes
and adding scale_color_manual
will add a legend.aes
移动color
并添加scale_color_manual
将添加一个图例。fill
aes and scale_fill_manual
fill
aes 和scale_fill_manual
key_glyph
to " path"
for all three geomskey_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.