![](/img/trans.png)
[英]How to change the text and title of legend in ggplot with several variables
[英]How plot legend in ggplot graph with several variables?
我有以下代码
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 有两种颜色,这也很棒)
也许这就是你正在寻找的。
aes
移动color
并添加scale_color_manual
将添加一个图例。fill
aes 和scale_fill_manual
key_glyph
以“ path"
为所有三个geoms使用一些随机示例数据试试这个:
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.