![](/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.