2017-10-20 111 views
0

我想绘制使用geom_barposition = "dodge"的钻石比例。这是我所做的。ggplot2:使用geom_bar绘制正确的比例

library(ggplot2) 

ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut)) 

下面的图片告诉我每个cut类型有多少颗钻石。

enter image description here

现在让我们做一些花哨。

ggplot(data = diamonds) + geom_bar(mapping = aes(x = cut, fill = clarity), position = "dodge") 

图像下面通过clarity每个cut类型分组钻石提供的计数。

enter image description here

我想这样做是得到相同的闪避情节同上,但显示比例,而不是数

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

+1

无需一个附加列:'ggplot(数据=菱形)+ geom_bar(映射= AES(X =切,Y = ..count .. /sum(..count ..),fill = clarity),position =“dodge”)' –

+0

@MauritsEvers没有给出想要的结果(例如,运行它并查看“cut = ideal”的值,并且'清晰度= VS2' - 不是0.23)。 – Lyngbakr

+0

@Lyngbakr是的,你是对的! OP希望分数*每个(剪辑)组*。我的解决方案给出的总分数。在这种情况下,我会手动计算每个分组的分数,并使用geom_bar(stat =“identity”,...)绘制@Wimpel建议的图形。 –

回答

2

可以尝试

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") 

enter image description here

+0

谢谢你,这就是我一直在寻找的。 –

-1

创建正确的百分比列(名为“百分比”),并使用

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) 

您还可以计算百分比内联,如Maurits的埃弗斯建议。

+0

它要求的比例不是百分比。 – Lyngbakr

+0

啊,你是对的..错过了:) – Wimpel