簡體   English   中英

ggplot2繪制與屬於不同組的實線相同顏色的虛線

[英]ggplot2 draw dashed lines of same colour as solid lines belonging to different groups

我試圖為每組繪制2種不同顏色的2條實線,但也在這些線條周圍添加相同顏色的虛線,然后添加圖例。 出於某種原因,我在使用“虛線”或“虛線”時遇到了麻煩,看起來我正在兩次繪制虛線。 我也沒有正確的傳說,我得到錯誤Adding another scale for 'colour', which will replace the existing scale

你能幫我弄清楚我做錯了什么嗎? 這是一個示例數據集和我嘗試過的內容:

x <- c(10, 20, 50, 10, 20, 50)
mean = c(52.4, 98.2, 97.9, 74.1, 98.1, 97.6)
group = c(1, 1, 1, 2,2,2) 
upper = c(13.64, 89, 86.4, 13.64, 89, 86.4)
lower = c(95.4, 99.8, 99.7, 95.4, 99.8, 99.7)
data <- data.frame(x=x,y=mean, group, upper, lower)

ggplot(data, aes(x = x, y= mean, group = as.factor(data$group), colour=as.factor(data$group))) + geom_line() + geom_point() + geom_line(data=data,aes(x=x, y=lower, group = as.factor(data$group), colour=as.factor(data$group), linetype="dotted")) + geom_line(data=data,aes(x=x, y=upper, group = as.factor(data$group), colour=as.factor(data$group), linetype="dotted")) + scale_color_manual(values=c("red", "blue")) +  scale_colour_discrete(name="Groups") 

我也試過geom_ribbon ,再次沒有運氣的分組部分......

ggplot(data, aes(x = x, y= mean, group = group)) + geom_line() +
geom_ribbon(aes(ymin = lower, ymax = upper)) +
geom_line(aes(y = mean), colour = "Mean")) +
scale_colour_manual(name = "", values = c("Group1", "Group2"))

要添加虛線,您應該添加2個geom_line()調用,在aes()提供y值。 不需要輸入data=groups=參數,因為它們與ggplot()調用中的相同。 linetype="dotted"應放在aes()調用之外。 對於顏色,您只需要一個scale_color_manual() 要從圖例中刪除虛線圖案,可以使用函數guides()guide_legend()覆蓋美學。

ggplot(data, aes(x = x, y= mean, group = as.factor(data$group), 
                          colour=as.factor(data$group))) + 
  geom_line() + geom_point() + 
  geom_line(aes(y=lower),linetype="dotted") + 
  geom_line(aes(y=upper),linetype="dotted")+
  scale_color_manual(name="Groups",values=c("red", "blue"))+
  guides(colour = guide_legend(override.aes = list(linetype = 1)))

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM