我有以下代码
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)))
我的图在看:
如何添加图例,以说明哪种颜色对应于哪个变量? (如果您帮我描绘一种颜色的条形图,那将是很好的,当它是正数时,值是正的,而另一种颜色是正色的;然后在图例中告诉变量prodVScons是2种颜色)
答案 0 :(得分:0)
也许这就是您想要的。
color
中移动aes
并添加scale_color_manual
之后,我将添加一个图例。fill
aes和scale_fill_manual
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)