显示ggplot中的百分比

时间:2014-09-02 09:36:20

标签: r graphics ggplot2 bar-chart percentage

我有一个二进制变量的数据集,如下所示。

M4 = matrix(sample(1:2,20*5, replace=TRUE),20,5)
M4 <- as.data.frame(M4)
M4$id <- 1:20

我使用下面的代码生成了堆积条形图

library(reshape)
library(ggplot2)
library(scales)
M5 <- melt(M4, id="id")
M5$value <- as.factor(M5$value)
ggplot(M5, aes(x = variable)) + geom_bar(aes(fill = value), position = 'fill') +
  scale_y_continuous(labels = percent_format())

现在我希望每个条形图中每个字段的百分比显示在图表中,以便每个条形图达到100%。我尝试了123以及几个类似的问题,但我无法找到适合我情况的任何示例。我该如何管理这项任务?

3 个答案:

答案 0 :(得分:2)

试试这个方法:

test <- ggplot(M5, aes(x = variable, fill = value, position = 'fill')) + 
  geom_bar() +
  scale_y_continuous(labels = percent_format()) +
  stat_bin(aes(label=paste("n = ",..count..)), vjust=1, geom="text")
test

enter image description here

编辑:给出百分比并使用scale s包:

require(scales)
test <- ggplot(M5, aes(x = variable, fill = value, position = 'fill')) + 
  geom_bar() +
  scale_y_continuous(labels = percent_format()) +
  stat_bin(aes(label = paste("n = ", scales::percent((..count..)/sum(..count..)))), vjust=1, geom="text")
test

enter image description here

答案 1 :(得分:1)

您可以使用sjPlot-package中的sjp.stackfrq功能(请参阅examples here)。

M4 = matrix(sample(1:2,20*5, replace=TRUE),20,5)
M4 <- as.data.frame(M4)
sjp.stackfrq(M4)
# alternative colors: sjp.stackfrq(M4, barColor = c("aquamarine4", "brown3"))

enter image description here

可以使用各种参数来确定绘图外观......

答案 2 :(得分:0)

我非常喜欢使用ggplot本身创建的隐式信息,如本文所述:

using the ggplot_build() function

从我的观点来看,这为最终控制ggplot图表的外观提供了很多机会。

希望这会有所帮助

汤姆

相关问题