2012-12-09 22 views
2

如果對象包含我想在分配時解析的其他變量,那麼將ggplot2 grob賦值給變量的正確方法是什麼?將ggplot grob分配給賦值時解析所有值的變量

例如:
xposypos是,我想解決的值。 我將geom_text分配給ptext,然後我想將它添加到一些圖中,比如說p1和p2。

xpos <- .2 
ypos <- .7 

ptext <- geom_text(aes(x = xpos, y = ypos, label = "Some Text")) 

,我可以添加ptext另一個情節,一切按預期工作

## adding ptext to a plot 
p1 <- qplot(rnorm(5), rnorm(5)) 
p1 + ptext 

但是,刪除(或改變)xpos & ypos給出了意外的結果。

rm(xpos, ypos) 

p2 <- qplot(rnorm(5), rnorm(5)) 
p2 + ptext 
# Error in eval(expr, envir, enclos) : object 'xpos' not found 

這是怎麼回事?

回答

3

您應該將xposypos放在數據框中。在你的例子中:

coords = data.frame(xpos=.2, ypos=.7) 

ptext <- geom_text(data=coords, aes(x = xpos, y = ypos, label = "Some Text")) 

## adding ptext to a plot 
p1 <- qplot(rnorm(5), rnorm(5)) 
p1 + ptext 

# removing (or altering) the old coords data frame doesn't change the plot, 
# because it was passed by value to geom_text 
rm(coords) 

p2 <- qplot(rnorm(5), rnorm(5)) 
p2 + ptext 
+0

這樣做,非常感謝你! –