R - ggplot geom_bar:aes(group = 1)的含义 [英] R - ggplot geom_bar: meaning of aes(group = 1)

查看:2375
本文介绍了R - ggplot geom_bar:aes(group = 1)的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是R新手,目前正在学习r4ds.had.co.nz 3.7节的geom_bar。我运行这样的代码:

  library(ggplot2)
ggplot(data = diamonds)+ geom_bar(mapping = aes(x = cut,y = ..prop ..,group = 1))

然后我有这样的情节:



重点是,如果我排除组= 1部分: data = diamonds)+ geom_bar(mapping = aes(x = cut,y = ..prop ..))

该情节将是错误的,



<但是,如果我通过group = 2或group =x替换group = 1,则情节看起来仍然正确。所以我不太明白group = 1的含义以及如何使用它。

group =whatever是一个哑元分组来覆盖默认行为,这里(这里)是由 cut 分组,并且通常是由x变量组成的。 geom_bar 的默认值是用x变量进行分组,以分别计算x变量每个级别的行数。例如,在这里,缺省值为 geom_bar 返回 cut 等于Fair的行数,好等。

然而,如果我们想要比例,那么我们需要考虑 cut 在一起。在第二个图中,数据首先按照 cut 分组,因此 cut 的每个级别都是分开考虑的。 Fair in Fair的比例为100%,Good in Good等比例也为100%。 group = 1 (或 group =x 等)可以防止这种情况发生,因此每个切割级别的比例将相对于所有切割级别。


I am new to R, and currently learning geom_bar on section 3.7 of r4ds.had.co.nz. I run a code like this:

library(ggplot2)
ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, y = ..prop.., group = 1))

Then I have this plot:

The point is, if I exclude the "group = 1" part:

library(ggplot2)
ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, y = ..prop..))

The plot will be wrong,

But if I replace group = 1 by group = 2 or group = "x", the plot still looks correct. So I don't quite understand the meaning of group = 1 here and how to use it.

解决方案

group="whatever" is a "dummy" grouping to override the default behavior, which (here) is to group by cut and in general is to group by the x variable. The default for geom_bar is to group by the x variable in order to separately count the number of rows in each level of the x variable. For example, here, the default would be for geom_bar to return the number of rows with cut equal to "Fair", "Good", etc.

However, if we want proportions, then we need to consider all levels of cut together. In the second plot, the data are first grouped by cut, so each level of cut is considered separately. The proportion of Fair in Fair is 100%, as is the proportion of Good in Good, etc. group=1 (or group="x", etc.) prevents this, so that the proportions of each level of cut will be relative to all levels of cut.

这篇关于R - ggplot geom_bar:aes(group = 1)的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆