ggplot geom_bar: meaning of aes(group = 1)

前端 未结 2 1616
失恋的感觉
失恋的感觉 2020-12-04 15:32

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         


        
2条回答
  •  抹茶落季
    2020-12-04 16:25

    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.

提交回复
热议问题