2009-11-24 22 views
6

我在獲取ggplot2的時候遇到了一些麻煩,因爲我想要。基本上,我想比較實際的觀察值和近似值,並將它們放在一個單獨的圖中。例如,傳說中的問題,同時繪製兩個數據的數據。框架

> library(ggplot2) 
> df.actual <- data.frame(x = 1:100, y = (1:100) * 2) 
> df.approx <- data.frame(x = 1:150, y = (1:150) * 2 + 5 + rnorm(150, mean = 3)) 
> ggplot() + geom_point(aes(x, y), data = df.actual) + geom_line(aes(x,y), data = df.approx) 

我的問題是我無法顯示圖例。我在某處讀到ggplot2的傳說不太靈活(?)。理想情況下,

  • 標題= '類型'
  • 鍵一個傳說:一個黑色實心點,黑線
  • 密鑰標籤: '實際', '近似'
  • legend.position = 'topright'

謝謝。

回答

6

試試這個,讓你開始

ggplot() + 
    geom_point(aes(x, y, colour = "actual"), data = df.actual) + 
    geom_line(aes(x, y, colour = "approximate"), data = df.approx) + 
    scale_colour_discrete("Type") 
+1

感謝哈德利, 我想區分日期黑白情節。正如我所描述的那樣,有可能有一個圖例,其中兩個鍵是點和線? – knguyen 2009-11-24 15:05:06

4

這是某種形式的黑客通過網格對象的操作來修改傳說:

library("ggplot2") 
df.actual <- data.frame(x=1:100, y=(1:100)*2) 
df.approx <- data.frame(x=1:150, y=(1:150)*2 + 5 + rnorm(150, mean=3)) 
p <- ggplot() + 
    geom_point(aes(x, y, colour="Actual"), data=df.actual) + 
    geom_line(aes(x, y, colour="Approximate"), data=df.approx) + 
    scale_colour_manual(name="Type", 
         values=c("Actual"="black", "Approximate"="black")) 
library("grid") 
grob <- ggplotGrob(p) 
tmp <- grid.ls(getGrob(grob, "key.segments", grep=TRUE, global=TRUE))$name 
grob <- removeGrob(grob, tmp[1]) # remove first line segment in legend key 
tmp <- grid.ls(getGrob(grob, "key.points", grep=TRUE, global=TRUE))$name 
grob <- removeGrob(grob, tmp[2]) # remove second point in legend key 
grid.draw(grob) 

ggplot2 output http://img134.imageshack.us/img134/8427/ggplotlegend.png

+0

感謝您的可重複的例子。 ggplot2應該自動處理這種類型的圖例,所以我將它添加到我的待辦事項列表中。 – hadley 2009-11-26 03:08:22

相關問題