简体   繁体   English

ggplot2:使用geom_bar绘制正确比例

[英]ggplot2: plot correct proportions using geom_bar

I am trying to plot proportion of diamonds using geom_bar and position = "dodge" . 我正在尝试使用geom_barposition = "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=idealclarity = VS2 ,该比例应为5071/21551 = 0.23

You can try 你可以试试

library(tidyverse)
diamonds %>%
  count(cut, clarity) %>% 
  group_by(cut) %>% 
   mutate(Sum=sum(n)) %>% 
   mutate(proportion = n/Sum) %>% 
  ggplot(aes(y=proportion, x=cut,fill=clarity)) +
   geom_col(position = "dodge")

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM