1

我想创建一个这样的条形图:

library(ggplot2)

# Dodged bar charts
ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar(position="dodge")

但是,我希望通过切割类别(“一般”、“好”、“非常好”......)来获得属于每个“清晰度”类别的观察百分比,而不是计数。

有了这个 ...

# Dodged bar charts
ggplot(diamonds, aes(clarity, fill=cut)) + 
geom_bar(aes(y = (..count..)/sum(..count..)), position="dodge")

我在 y 轴上得到百分比,但这些百分比忽略了切割因子。我希望所有红色条总和为 1,所有黄色条总和为 1,依此类推。

有没有一种简单的方法可以使这项工作无需手动准备数据?

谢谢!

PS:这是这个stackoverflow问题的后续

4

1 回答 1

1

您可以sjp.xtabsjPlot-package中使用:

sjp.xtab(diamonds$clarity, 
         diamonds$cut, 
         showValueLabels = F, 
         tableIndex = "row", 
         barPosition = "stack")

在此处输入图像描述

总和为 100% 的堆叠组百分比的数据准备应为:

data.frame(prop.table(table(diamonds$clarity, diamonds$cut),1))

因此,你可以写

mydf <- data.frame(prop.table(table(diamonds$clarity, diamonds$cut),1))
ggplot(mydf, aes(Var1, Freq, fill = Var2)) + 
  geom_bar(position = "stack", stat = "identity") +
  scale_y_continuous(labels=scales::percent)

编辑:这个将每个类别(一般,良好...)加起来为 100%,使用2inprop.tableposition = "dodge"

mydf <- data.frame(prop.table(table(diamonds$clarity, diamonds$cut),2))
ggplot(mydf, aes(Var1, Freq, fill = Var2)) + 
    geom_bar(position = "dodge", stat = "identity") +
    scale_y_continuous(labels=scales::percent)

或者

sjp.xtab(diamonds$clarity, 
         diamonds$cut, 
         showValueLabels = F, 
         tableIndex = "col")

在此处输入图像描述

使用 dplyr 验证最后一个示例,总结每个组中的百分比:

library(dplyr)
mydf %>% group_by(Var2) %>% summarise(percsum = sum(Freq))

>        Var2 percsum
> 1      Fair       1
> 2      Good       1
> 3 Very Good       1
> 4   Premium       1
> 5     Ideal       1

(有关更多绘图选项和示例,请参阅此页面sjp.xtab...)

于 2015-04-15T11:41:57.203 回答