2012-12-03 111 views
1

假設我有一組數據,並且想要爲每個與它一起繪製的幾何圖形添加一個圖例。例如:如何在ggplot2中添加幾何圖例?

x <- rnorm(100, 1) 
qplot(x = x, y = 1:100, geom = c("point", "smooth")) 

而且它會是這個樣子:

enter image description here

現在,我想補充一個傳奇所以會這樣說:

Legend title 
* points [in black] 
--- smoothed [in blue] 

在哪裏我指定了「傳奇頭銜」,「點數」和「平滑」名字。

我該怎麼辦?

回答

2

添加額外信息的最簡單方法是使用註釋而不是圖例。 (我知道這是一個玩具的例子,但ggplot是明智的,因爲只有一種點和一種線的時候,不包括圖例,你可以創造一個圖例,但它默認會佔用更多的空間和墨水而不是必要的,並且需要更多的工作,當只有一種點時,它的含義應該從x和y軸上的標籤以及圖的一般上下文中清楚地表明,缺少其他信息,讀者會推斷這條線是對點的函數擬合的結果,他們唯一不知道的是灰色誤差區域的具體函數和含義,可以是一個簡單的標題,註釋,或圖形外的文本。

#Sample data in a dataframe since that works best with ggplot 
set.seed(13013) 
testdf <- data.frame(x <- rnorm(100, 1),y <- 1:100) 

一種選擇是一個標題:

ggplot(testdf , aes(x = x, y = y)) + geom_point()+ 
    stat_smooth(method="loess")+ 
    xlab("buckshot hole distance(from sign edge)")+ 
    ylab("speed of car (mph)")+ 
    ggtitle("Individual Points fit with LOESS (± 1 SD)") 

sample ggplot with title

另一種選擇是一個註釋層。在這裏,我使用均值和最大值函數來猜測文本的合理位置,但是可以使用實際數據做得更好,並且可以使用像size=3這樣的參數來縮小文本大小。

ggplot(testdf , aes(x = x, y = y)) + geom_point()+ 
    stat_smooth(method="loess")+ 
    xlab("buckshot hole distance (from sign edge)")+ 
    ylab("speed of car (mph)")+ 
    annotate("text", x = max(testdf$x)-1, y = mean(testdf$y), 
    label = "LOESS fit with 68% CI region", colour="blue") 

sample ggplot with annotation

+0

謝謝你的解決方法。不過,我確實需要一個傳奇。這是一個非常基本的要求,我很驚訝像ggplot2這樣的複雜軟件包無法處理它。 – J4y

1

的一個快速方法來標註ggplot情節,就是用geom_text

x <- rnorm(100, 1) 
y = 1:100 
library(ggplot2) 
dat <- data.frame(x=x,y=y) 
bp <- ggplot(data =dat,aes(x = x, y = y))+ 
     geom_point()+ geom_smooth(group=1) 


bp <- bp +geom_text(x = -1, y = 3, label = "* points ", parse=F) 
bp <- bp +geom_text(x = -1, y = -1, label = "--- smoothed ", parse=F,color='blue') 
bp 

enter image description here

+0

感謝您的嘗試。 +1,因爲我可以用這種方式創建一個臨時圖例。我會等待,看看有沒有人知道如何做出正確的傳說。 – J4y