ggplot2 中继承的限制是什么?

What are the limits to inheritance in ggplot2?

我一直在尝试解决有关 ggplot2 的一些问题,以及补充参数如何继承自第一部分 ggplot()。具体来说,如果继承超出了 geom_*** 部分。

我有一个数据直方图:

ggplot(data = faithful, aes(eruptions)) + geom_histogram()

它生成了一个精美的图表,尽管中断是默认的。在我看来(一个承认的新手),geom_histogram() 正在从 ggplot() 继承数据规范。如果我想以更智能的方式设置休息时间,我可以使用这样的过程:

ggplot(data = faithful, aes(eruptions)) + 
geom_histogram(breaks = seq(from = min(faithful$eruptions), 
                            to = max(faithful$eruptions), length.out = 10))

然而,这里我在 geom_histogram() 函数中重新指定我想要的 faithful$eruptions。如果不重新指定,我一直无法找到一种表达方式。此外,如果我在 geom_histogram() 中使用 data = 参数,并在 minmax 中仅指定 eruptionsseq() 仍然无法理解我的意思是 faithful 数据集。

我知道 seq 不是 ggplot2 的一部分,但我想知道它是否可以继承,因为它绑定在 geom_histogram() 中,它本身继承自 ggplot().我只是使用了错误的语法,还是这可能?

根据 ggplot2 文档,似乎 + 运算符实际上是 +.gg 函数,允许将以下对象添加到 ggplot 对象: data.frame, uneval, layer, theme, scale, coord, facet

geom 函数是创建从 ggplot 对象 "above" 继承 dataaes 的层的函数,除非另有说明。

但是 ggplot 对象和函数 "live" 在全局环境中,因此调用 seq 之类的函数不会从上面列出的对象创建 ggplot 对象,也不会继承 ggplot 对象的主题(使用 + 运算符应用于上面列出的对象)生活在不包含对象 eruptions

的全局环境中

请注意,您要查找的术语不是 "inheritance",而是非标准评估 (NSE)。 ggplot 提供了几个地方,您可以在其中通过列名而不是完整引用 (NSE) 来引用数据项,但这些只是 geom_* 层的 mapping 参数,甚至在您使用 aes 时也是如此。这些工作:

ggplot(faithful) + geom_point(aes(eruptions, eruptions))
ggplot(faithful) + geom_point(aes(eruptions, eruptions, size=waiting))

以下内容不起作用,因为我们指的是 aesmapping 之外的 waiting(注意 geom_* 的第一个参数是 mapping arg):

ggplot(faithful) + geom_point(aes(eruptions, eruptions), size=waiting)

但这行得通:

ggplot(faithful) + geom_point(aes(eruptions, eruptions), size=faithful$waiting)

虽然不同,因为现在 size 被乱七八糟地解释,而不是被规范化为 mapping 的一部分。

在您的情况下,由于 breaks 不是 aes/mapping 规范的一部分,您不能使用 NSE,只能使用完整参考。一些可能的解决方法:

ggplot(data = faithful, aes(eruptions)) + geom_histogram(bins=10)  # not identical
ggplot(data=faithful, aes(eruptions)) + 
  geom_histogram(
    breaks=with(faithful,  # use `with`
      seq(from=max(eruptions), to=min(eruptions), length.out=10)
  ) )

并且没有 NSE,但打字少了一点:

ggplot(data=faithful, aes(eruptions)) + 
  geom_histogram(
    breaks=do.call(seq, c(as.list(range(faithful$eruptions)), len=10))
  )