[英]ggplot2: plot correct proportions using geom_bar
I am trying to plot proportion of diamonds using geom_bar
and position = "dodge"
. 我正在尝试使用
geom_bar
和position = "dodge"
绘制钻石的比例。 Here is what I have done. 这是我所做的。
library(ggplot2)
ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut))
The image below tell me how many diamonds are there for each cut
type. 下图告诉我每种
cut
类型有多少颗钻石。
Now let's do something fancy. 现在,让我们做一些花哨的事情。
ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge")
The image below provides count of by grouping diamonds by clarity
for each cut
type. 下图提供了按每种
cut
类型的clarity
将钻石分组的计数。
What I would like to do is get the same dodge plot as above but showing proportion instead of count . 我想做的是得到与上述相同的躲避图,但显示比例而不是数量 。
For example, for cut=ideal
and clarity = VS2
, the proportion should be 5071/21551 = 0.23
. 例如,对于
cut=ideal
且clarity = VS2
,该比例应为5071/21551 = 0.23
。
create a column with the correct percentages (named "percentage"), and use 创建具有正确百分比(称为“百分比”)的列,然后使用
require(ggplot2)
require(scales)
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, y = percentage, fill = clarity), position = "dodge") +
scale_y_continuous(labels = scales::percent)
You can also calculate the percentage inline, as Maurits Evers suggests. 您还可以按照Maurits Evers的建议计算内联百分比。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.