【问题标题】:R - Aggregate Percentage for Stacked Bar Charts using ggplot2R - 使用 ggplot2 堆积条形图的聚合百分比
【发布时间】:2015-01-16 10:28:52
【问题描述】:

我有一些如下所示的数据。我的目标是为它们生成堆积条形图,但我需要将值显示为百分比。我已经设法将数据融合到正确的形状并绘制堆叠条,但值远远超过 100%(在我的实际数据集中,一些值加起来达到 8000+)。设置 ggplot2 以便我可以创建百分比堆积条形图的正确方法是什么?

#Raw Data
x   A    B    C
1   5   10   14
1   4    4   14
2   5   10   14
2   4    4   14
3   5   10   14
3   4    4   14

#Aggregate
data < read.table(...); 
data <- aggregate(. ~ x, data, sum) #<---- Sum to Average? 
x   A    B    C
1   9   14   28
2   9   14   28
3   9   14   28

#Melt Data
data <- melt(data,"x")
  x variable value
1 1        A     9
2 2        A     9
3 3        A     9
4 1        B    14
5 2        B    14
6 3        B    14
7 1        C    28
8 2        C    28
9 3        C    28

#Plot stack bar chart counts
ggplot(data, aes(x=1, y=value, fill=variable)) + geom_bar(stat="identity") + facet_grid(.~x)

我希望在融化之前得到这样的东西,这样我就可以融化它并将其绘制为堆积条形图,但我不知道如何处理这个问题。

#Ideal Data Format - After Aggregate, Before Melt
x     A       B       C
1   17.64   27.45   54.90
2   17.64   27.45   54.90
3   17.64   27.45   54.90

问:使用 ggplot2 创建带有百分比的堆积条形图的正确方法是什么?


【问题讨论】:

  • 你要使用facet_grid(.~x)吗?

标签: r ggplot2


【解决方案1】:

您可以使用熔体数据计算比例。然后,您可以绘制一个图形。在这里,您可以使用dplyr 包中的group_by 计算x 的每个级别的比例。您还有其他选择。如果您想阅读mutate 行,就像“对于x 的每个级别,我想得到percent。”为了删除分组变量x,我最后添加了ungroup()

library(dplyr)
library(ggplot2)

### foo is your melt data
ana <- mutate(group_by(foo, x), percent = value / sum(value) * 100) %>%
       ungroup()

### Plot once
bob <- ggplot(data = ana, aes(x = x, y = percent, fill = variable)) +
       geom_bar(stat = "identity") +
       labs(y = "Percentage (%)")

### Get ggplot data
caroline <- ggplot_build(bob)$data[[1]]

### Create values for text positions
caroline$position = caroline$ymax + 1

### round up numbers and convert to character. Get unique values
foo <- unique(as.character(round(ana$percent, digits = 2)))

### Create a column for text
caroline$label <- paste(foo,"%", sep = "")

### Plot again
bob + annotate(x = caroline$x, y = caroline$position,
               label = caroline$label, geom = "text", size=3) 

数据

foo <-structure(list(x = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), variable = structure(c(1L, 
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"), 
value = c(9L, 9L, 9L, 14L, 14L, 14L, 28L, 28L, 28L)), .Names = c("x", 
"variable", "value"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9"))

【讨论】:

  • 感谢您的回复。后续问题:如何在相关部分顶部显示标签?即蓝色标签上写着“C - 54.90%”。
  • @lolcodez 这需要更多的工作。让我在今天晚些时候更新我的建议。
  • @lolcodez 看看this post。您可以找到如何添加注释。