[英]Add legend to ggplot2 line with point plot
我對ggplot2中的圖例有疑問。 我設法在同一張圖中繪制兩條線和兩個點,並希望使用兩種顏色添加圖例。 這是使用的代碼
P <- ggplot() + geom_point(data = data_p,aes(x = V1,y = V2),shape = 0,col = "#56B4E9") + geom_line(data = data_p,aes(x = V1,y = V2),col = "#56B4E9")+geom_point(data = data_p,aes(x = V1,y = V3),shape = 1,col = "#009E73") + geom_line(data = data_p,aes(x = V1,y = V3),col = "#009E73")
輸出是在此處輸入圖像描述
我嘗試使用scale_color_manual和scale_shape_manual和scale_line_manual,但是它們不起作用。
P + scale_color_manual(name = "group",values = c('#56B4E9' = '#56B4E9','#009E73' = '#009E73'),
breaks = c('#56B4E9','#009E73'),labels = c('B','H')) +
如果可以幫助您,這是簡單的數據。
5 0.49216 0.45148
10 0.3913 0.35751
15 0.32835 0.30361
我將分兩個步驟解決這個問題。
通常,為了獲得指南中的內容,ggplot2希望您將像顏色之類的“美學”放入aes()函數中。 我通常在ggplot()中執行此操作,而不是針對每個“ geom”單獨執行此操作,尤其是如果在單個數據幀中一切都有意義的話。
我的第一步是稍微重新制作數據框。 我將使用軟件包tidyr(tidyverse的一部分,例如ggplot2,它非常適合重新格式化數據並值得您隨時學習),並執行類似的操作
#key is the new variable that will be your color variable
#value is the numbers that had been in V2 and V3 that will now be your y-values
data_p %>% tidyr::gather (key = "color", value = "yval", V2, V3)
#now, I would rewrite your plot slightly
P<-(newdf %>% ggplot(aes(x=V1,y=yval, colour=color))
#when you put the ggplot inside parentheses,
#you can add each new layer on its own line, starting with the "+"
+ geom_point()
+ geom_line()
+ scale_color_manual(values=c("#56B4E9","#009E73"))
#theme classic is my preferred look in ggplot, usually
+ theme_classic()
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.