使 ggplot2 将多个数据集保存到 ggplot2 对象

make ggplot2 save several datasets to ggplot2 object

我正在为一个包开发一个函数来构建一个相对复杂的 ggplot2 图。 该图需要 几个 数据帧。 我知道 ggplot2 可以做到这一点,如下例所示——情节看起来不错。

当我将这样一个对 ggplot2 的调用包装在一个函数中,然后使用函数 return ggplot2 对象(例如,g)时,问题就出现了:当我尝试打印这个时对象 g,ggplot2 对我大喊它找不到这个或那个数据。 在函数 中工作正常。

我的假设是这不起作用,因为 ggplot2 在其对象中仅保存 一个 数据集。

这是我的测试:

df1 <- data.frame(x=rnorm(10), y=rnorm(10))
df2 <- data.frame(x=rnorm(10), y=rnorm(10))
library(ggplot2)
g <- ggplot(data = df1, aes(x=x, y=y))
g <- g + geom_point()
g <- g + geom_point(data = df2, aes(x=x, y=y))
g
print(g$data)

看起来不错,但 g$data 只是:

            x           y
1  -0.6877237 -1.04801924
2  -1.0866550  1.65779036
3  -1.7649836 -0.08788452
4  -0.6459257 -0.22692532
5   0.5649141  0.51516430
6  -0.3117237 -1.84447991
7  -0.5771836 -0.65616395
8  -0.7666694  1.44671890
9   0.1687370  0.94250971
10 -0.3278663  1.00276428

看起来 ggplot2 删除了另一个 df。

我做对了吗? 如何让 ggplot2 记住多个数据集?

也许这会让您参与其中...

df1 <- data.frame(x=rnorm(10), y=rnorm(10))
df2 <- data.frame(x=rnorm(10), y=rnorm(10))

library(ggplot2)
g <- ggplot(data=cbind(df1, df2))
g <- g + geom_point(data = df1, aes(x=x, y=y))
g <- g + geom_point(data = df2, aes(x=x, y=y))
g

让你得到和以前一样的情节...

str(g)

但是我们现在已经把数据变成了一个数据帧。

List of 9
 $ data       :'data.frame':    10 obs. of  4 variables:
  ..$ x: num [1:10] 1.398 -0.379 0.486 0.813 1.057 ...
  ..$ y: num [1:10] 0.0499 -2.5607 0.2624 0.7812 0.5015 ...
  ..$ x: num [1:10] 1.283 -0.786 -0.223 -0.89 -0.103 ...
  ..$ y: num [1:10] -2.19 -0.468 -0.436 -2.502 -0.143 ...

问题是你的假设是错误的。 ggplot 会将绘图的所有数据存储在对象中,只是可能不在您认为会存储的位置。如果您将数据放在对 ggplot() 的调用中,它将位于 $data 属性 中。如果您在图层中指定数据,它将包含在该图层中。

在您的示例中,df1 如您观察到的那样位于 g$data,而 df2 位于 g$layers[[2]]$data。所以这两个数据集都在ggplot对象中。