【问题标题】:geom_bar stops working when group added添加组时 geom_bar 停止工作
【发布时间】:2012-11-14 01:36:54
【问题描述】:

使用这些数据:

library(ggplot2)
dd <- data.frame(id = c("A", "A", "B", "B"), prepost = c("pre", "post"), 
         value = 1:4)

这个有效:

qplot(id, value, data = dd, fill = prepost, geom = "bar")

但是,下一个给出了指示的错误消息。两者的唯一区别是在命令末尾添加了group = prepost;但是,因为我们已经写了fill = prepost,所以无论如何它应该是默认组。

> qplot(id, value, data = dd, fill = prepost, geom = "bar", group = prepost)
 Error in pmin(y, 0) : object 'y' not found

我们可以通过像这样添加stat = "identity" 来修复最后一个:

qplot(id, value, data = dd, fill = prepost, geom = "bar", group = prepost, 
      stat = "identity")

我有两个问题:

(a) 为什么给出错误信息的qplot 在其他人正常工作时却不工作?

(b) 如果我们使用连续的y 美学和geom_bar,那么如果不指定stat 会发生什么?从第一个 qplot 开始,似乎在这种情况下它的行为就像 stat="identity" 但在存在 group 时指定 stat="identity" 或不显示差异。

(顺便说一句,这个问题似乎有些相关,尽管它的不同之处在于它似乎无法回答这个问题:Issue with ggplot2, geom_bar, and position="dodge": stacked has correct y values, dodged does not

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    一个好问题!

    我将回应@joran 之前的评论

    我发现人们一旦学会停止使用 qplot,就不会再对 ggplot 感到困惑了

    您的qplot 呼叫可以使用

    重新创建
    ggplot(dd) + geom_bar(aes(x = id, y = value, fill = prepost))
    

    现在,如果您阅读了geom_bar 的帮助,它列出了它所理解的美学,group 不是其中之一(所以当您这样做时,您可能无法期望它按您的意愿工作)

    如果您阅读group 的帮助,您会发现它是一种美学,允许您覆盖所有离散变量的默认交互。

    如果您单独按prepost 分组,则不会按离散的​​x 轴变量id 分组,默认值也会包含在内,

    因此

    ggplot(dd) + 
     geom_bar(aes(x=id, y = value, fill = prepost, group = interaction(id, prepost)))
    

    有效,但分组是完全多余的,因为这是默认设置。

    如果您只指定prepostid 作为分组,它会混淆stat_bin(处理数字以创建条形图值的基础方法。因此您需要改用stat_identity .


    编辑:正如下面 cmets 中的 OP 所指出的,这与 known issue 相关,并将在下一个版本(或 github 上的当前开发版本)中给出更好的警告

    来自新闻

    • stat_bin 现在与 set 或 映射 y 值。以前,可以使用stat_bin 和 还设置/映射 y 值;如果每组有一个 y 值,它将 显示数据中的 y 值,而不是 每组。此用法已弃用,将来将被删除 ggplot2 的版本。 (Winston Chang。修复 #632)

    【讨论】:

    • (a) 见?aes_group_order (b) 当你向ggplot提供融化的数据时,它不知道你是否汇总了数据。 stat=identity 只是告诉 ggplot 数据已经汇总。在 ?geom_bar 的帮助中包括:Sometimes, bar charts are used not as a distributional summary, but instead of a dotplot. Generally, it's preferable to use a dotplot (see geom_point) as it has a better data-ink ratio. However, if you do want to create this type of plot, you can set y to the value you have calculated, and use stat='identity'
    • @mnel,我认为这与qplot vs. ggplot1 since this fails too: ggplot(dd, aes(id, value, fill = prepost, group = prepost)) 没有任何关系+ geom_bar() ` 但在你的另一点上你是对的 - 我忘了id。然而,尽管当我们添加stat = "identity" 时它确实有效,所以仍然存在问题(b)。
    • @brandon,当然它适用于stat="identity"。我已经在问题中提到了这一点。
    • @user1189687,geom_barstat 的默认值为bin,因此调用stat_bin(正如我在答案中所说)
    • 我刚刚注意到,在这个链接github.com/hadley/ggplot2/blob/master/NEWS 中提到,用stat_bin 指定y 将在ggplot2 的下一个版本中发出警告,并且在未来它将是一个错误,所以我猜的意图是用户不应该指定ystat_bin
    猜你喜欢
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 2021-07-08
    • 2017-05-16
    相关资源
    最近更新 更多