2013-05-01 164 views
8

我想繪製每組2條不同顏色的2條實線,還要在這些線條的周圍添加相同顏色的虛線,然後添加一個圖例。出於某種原因,我在使用「虛線」或「虛線」時遇到問題,看起來我正在虛線上繪製兩次。我也沒有得到正確的傳說,我得到錯誤Adding another scale for 'colour', which will replace the existing scaleggplot2繪製了與屬於不同組的實線相同顏色的虛線

你能幫我弄清楚我做錯了什麼嗎? 下面是一個例子數據集,我曾嘗試:

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")) 

回答

23

要添加虛線你應該添加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))) 

enter image description here

+0

謝謝Didzis!也爲解釋!它似乎仍然像實線那樣以虛線先繪製,然後牢固......無論如何,它與我正在嘗試做的事更接近! – user2337032 2013-05-01 14:54:55

+0

這就是我正在尋找的東西(它奇怪地使用我的真實數據創建虛線,但我希望我可以通過更改主線的大小來修復它)。謝謝! – user2337032 2013-05-01 14:59:39

+0

@ user2337032更新我的答案以解決圖例中顯示虛線的問題。 – 2013-05-01 15:01:38

相關問題