ggplot geom_bar: meaning of aes(group = 1)

妖精的绣舞 提交于 2019-11-27 00:37:02

问题


I am 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.


回答1:


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.




回答2:


Group will help the plot to look at the specific rows that contain the specific cut and the proportion is found with respect to the whole database as in proportion of an ideal cut in the whole dataset.

If group is not used, the proportion is calculated with respect to the data that contains that field and is ultimately going to be 100% in any case. For instance, The proportion of an ideal cut in the ideal cut specific data will be 1.



来源:https://stackoverflow.com/questions/39878813/ggplot-geom-bar-meaning-of-aesgroup-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!