如果对象包含我想在分配时解析的其他变量,那么将ggplot2 grob分配给变量的正确方法是什么。
例如:
xpos
和ypos
是我想要解决的值。
我正在将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
&amp; ypos
会产生不良后果。
rm(xpos, ypos)
p2 <- qplot(rnorm(5), rnorm(5))
p2 + ptext
# Error in eval(expr, envir, enclos) : object 'xpos' not found
正确的方法是什么?
答案 0 :(得分:3)
您应该将xpos
和ypos
放在数据框中。在您的示例中:
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