ggplot2返回值

10

ggplot2stat_bin函数的文档说明它返回一个具有附加列的新数据帧。那么如何实际访问这个数据帧呢?

这是可行的吗?

simple <- data.frame(x = rep(1:10, each = 2))
tmp <- stat_bin(data=simple, binwidth=0.1, aes(x))
我已经弄清楚了,tmp是一个环境,ls(tmp)会显示环境中的对象,但在探索每个对象之后,我没有看到任何类似于所描述的返回值的东西。

我不确定,我认为计算是在打印时完成的,而且对用户来说不容易访问。 - Luciano Selzer
2个回答

9

注意:截至2022年5月24日,当前版本的ggplot2(3.3.6)不再支持下面描述的方法。您应该使用ggplot_build(tmp)代替print(tmp),如@showteth的现在已被接受的答案中所述。


正如Luciano Selzer所提到的,生成下面显示的表格的计算直到打印时才执行。(查看ggplot2:::print.ggplot()将显示,在其最后一行,它以不可见的形式返回表格,以便可以通过赋值进行进一步检查。)

tmp <- ggplot(data=simple) + stat_bin(aes(x), binwidth=0.1)
x <- print(tmp)
head(x[["data"]][[1]])
#   y count    x ndensity ncount density PANEL group ymin ymax xmin xmax
# 1 0     0 0.95        0      0       0     1     1    0    0  0.9  1.0
# 2 2     2 1.05        1      1       1     1     1    0    2  1.0  1.1
# 3 0     0 1.15        0      0       0     1     1    0    0  1.1  1.2
# 4 0     0 1.25        0      0       0     1     1    0    0  1.2  1.3
# 5 0     0 1.35        0      0       0     1     1    0    0  1.3  1.4
# 6 0     0 1.45        0      0       0     1     1    0    0  1.4  1.5

1
只有在与“ggplot”调用和“打印”配对之后,返回的数据框才存在?从OP的示例中,get('data',env = tmp)仅返回传递的sample数据框。 - Justin
@rmflight -- 我也发现ggplot2的内部非常难以检查。话虽如此,等到打印时才完成这些表格似乎是一个很好的设计决策,特别是考虑到ggplot的设计是在运行时更新和扩展图形。在用户最终添加+ stat_*()子句之前,执行这些计算没有意义... - Josh O'Brien
此外,一旦你知道它的存在,x <- print(tmp) 就和 tmp <- hist(simple) 一样容易。不过,如果 ?print.ggplot 至少像 ?hist 那样指出它确实有一个返回值,那就更好了。 - Josh O'Brien
1
@rmflight,关于文档的这些观点很好。如果我有空闲时间的话,我会尝试添加一个拉取请求来解决它们。 - joran
2
尝试记录现有的内部结构没有太大意义,因为即使我自己也不是很理解。在下一个版本中,温斯顿和我将进行重写,这应该会更简单、更易于扩展(并且可以调用所有统计函数以在绘图之外获取结果)。 - hadley
显示剩余3条评论

1
在 ggplot2 (3.3.5) 中,我无法通过 ggplot2:::print.ggplot() 获取返回的数据框,但是使用 ggplot_build 却能成功:
simple <- data.frame(x = rep(1:10, each = 2))
tmp <- ggplot(data=simple) + stat_bin(aes(x), binwidth=0.1)
# with ggplot_build
x <- ggplot_build(tmp)
head(x[["data"]][[1]])
#   y count   x xmin xmax density ncount ndensity flipped_aes PANEL group ymin ymax colour   fill size linetype alpha
# 1 2     2 1.0 0.95 1.05       1      1        1       FALSE     1    -1    0    2     NA grey35  0.5        1    NA
# 2 0     0 1.1 1.05 1.15       0      0        0       FALSE     1    -1    0    0     NA grey35  0.5        1    NA
# 3 0     0 1.2 1.15 1.25       0      0        0       FALSE     1    -1    0    0     NA grey35  0.5        1    NA
# 4 0     0 1.3 1.25 1.35       0      0        0       FALSE     1    -1    0    0     NA grey35  0.5        1    NA
# 5 0     0 1.4 1.35 1.45       0      0        0       FALSE     1    -1    0    0     NA grey35  0.5        1    NA
# 6 0     0 1.5 1.45 1.55       0      0        0       FALSE     1    -1    0    0     NA grey35  0.5        1    NA

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接