2

如果对象包含我希望在分配时解决的其他变量,那么将 ggplot2 grob 分配给变量的正确方法是什么。

例如:
xposandypos是我想要解析的值。我将 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

解决这个问题的正确方法是什么?

4

1 回答 1

3

您应该将xposandypos放入数据框中。在您的示例中:

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
于 2012-12-09T22:37:35.820 回答