2011-05-18 173 views
1

我試圖讓一個情節(使用ggplot),將geom_pointgeom_line,不同的變量在不同的顏色繪製的圖(根據scale_colour_manual(value = color)其中color是各種顏色的自定義數組)除到兩條水平黑線(geom_hline)。自定義圖例文本和顏色GGPLOT2

當我嘗試獲取定製的水平線的圖例文本時,出現了麻煩。看來,我只能有兩種之一:

  1. 水平線爲黑色,但此行圖例文本的顏色是不正確
  2. 此行圖例文本是正確的,但顏色水平線由上述scale_colour_manual顏色確定。

plot <- ggplot(data, aes(x = factor(Month), y = avgLoss, colour = type, order = -as.numeric(type))) 
     + geom_line() + geom_point() 

meanplus2sd <- mean(data$avgLoss) + 2*sd(data$avgLoss) 

plot <- plot + geom_hline(aes(yintercept = meanplus2sd), colour = "black") 

產生黑線,說在圖例中

plot <- plot + geom_hline(aes(yintercept = meanplus2sd, colour = "Mean + 2 Stdev.")) 

產生一條線,是在我的定義scale_colour_manual數組的下一個「黑」,但傳說文本"Mean + 2 Stdev."

除了獲取水平線以外,還可以獲取自定義顏色和圖例文字的任何幫助é標準geom_point + geom_line密謀會很好。謝謝。

+0

重複的例子(即一些代碼),將大大提高的機會,有人能回答這個問題。 – joran 2011-05-18 20:22:58

+2

按照這裏的指導:http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example給一個可重複的例子。這個問題應該不難,但答案將取決於您已經編寫的代碼。 – Chase 2011-05-18 20:25:14

+0

plot < - ggplot(data,aes(x = factor(Month),y = avgLoss,color = type,order = -as.numeric(type)))+ geom_line()+ geom_point() meanplus2sd < - mean (數據$ avgLoss)+ 2 * sd(數據$ avgLoss) plot < - plot + geom_hline(aes(yintercept = meanplus2sd),color =「black」)...在圖例中產生黑色的黑線 plot < - plot + geom_hline(aes(yintercept = meanplus2sd,color =「Mean + 2 Stdev。」))...產生一條線,它是我定義的scale_colour_manual數組中的下一個顏色,但圖例文本是「Mean + 2 Stdev。「 – Marver 2011-05-18 20:30:15

回答

1

想要得到您想要的一種方法是在原始數據框中包含水平黑線的數據。你的例子不完全可以重現,所以這可能不是你想要的完全代碼,但這是一般的想法:

添加行到'數據',每個級別'月',其中的值每行中的'avgLoss'等於'meanplus2sd'。您可能希望所有其他列都包含NAs。所以,

newData <- head(data,length(unique(data$Month))) 
newData$Month <- unique(data$Month) 
newData$avgLoss <- rep(meanplus2sd,length(unique(data$Month) 
newData$type <- rep('Mean + 2sd',length(unique(data$Month))) 
#Then set all other values in newData to NA...and, 
data <- rbind(data,newData) 

這應該讓你開始,你只需要確保顏色「黑」是在scale_colour_manual合適的位置,這可能需要一些擺弄。

+0

不是一個壞的解決辦法,除非我最終得到的點除了行。我還想過在geom_point之前繪製線條,然後讓水平線具有數組中的第一個顏色......然後,它只是爲了更改此函數的顏色數組。不過,我希望有一種明確的方法可以做到這一點,但這不是解決方法。 – Marver 2011-05-18 21:11:42

+1

如果您將相應的數據子集傳遞給geom_point和geom_line,我認爲不一定。將所有數據傳遞給geom_line,但省略geom_point中的水平線數據。 – joran 2011-05-18 21:44:34

0

註釋可能是一個不錯的選擇

x <- baseball 
tmp <- subset(x, team == c("CHN","NYA")) 
cols <- c("8" = "red","4" = "blue","6" = "darkgreen") 
meanplus2sd <- mean(tmp$rbi) + 2*sd(tmp$rbi) 

plot <- ggplot(tmp, aes(x = year, y = rbi, color = factor(team), order = -as.numeric(team))) + 
geom_line() + geom_point() + geom_hline(aes(yintercept = meanplus2sd)) + 
annotate("text",label="Mean + 2sd",x=min(tmp$year)+10, y=meanplus2sd+10)