ggplot2:使用 geom_bar 绘制正确的比例

chi*_*n s 0 r ggplot2

我正在尝试使用geom_bar和绘制钻石的比例position = "dodge"。这是我所做的。

library(ggplot2)

ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut))
Run Code Online (Sandbox Code Playgroud)

下图告诉我每种类型有多少颗钻石cut

在此输入图像描述

现在让我们做一些奇特的事情。

ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge")
Run Code Online (Sandbox Code Playgroud)

下图提供了按clarity每种cut类型对钻石进行分组的计数。

在此输入图像描述

我想做的是获得与上面相同的闪避图,但显示比例而不是计数

例如,对于cut=idealclarity = VS2,比例应为5071/21551 = 0.23

Rom*_*man 5

你可以试试

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")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述