r - 百分比标签到 100% 堆栈图尝试 "mutate"但不起作用

标签 r ggplot2

我必须在 ggplot2 中绘制带有 %age 标签的 100% 堆栈图表。在此处附加代码和我正在使用的数据。该问题可能是重复的,但已尝试解决方案,但出现错误或显示与下面相同的图。

输出:

structure(list(Category = structure(c(2L, 3L, 4L, 5L, 2L, 3L, 
4L, 5L, 2L, 3L, 4L, 5L, 2L, 3L, 4L, 5L, 2L, 3L, 4L, 5L), .Label = c("_", 
"1", "2", "3", "4"), class = "factor"), variable = structure(c(1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L, 
5L, 5L, 5L), .Label = c("IL1_Flag", "IL2_Flag", "IL3_Flag", "IL4_Flag", 
"IL5_Flag"), class = "factor"), value = c(21, 17, 16, 219, 20, 
17, 15, 207, 20, 15, 15, 204, 20, 15, 15, 202, 20, 15, 15, 208
)), row.names = c(NA, -20L), .Names = c("Category", "variable", 
"value"), class = "data.frame")

library(ggplot2)
library(Hmisc)
library(plyr)
library(reshape2)
library(dplyr)
library(scales)
library(tidyverse)

#Plotting the 100% Stacked Chart
ggplot() + geom_bar(
  aes(y = value, x = Category, fill = variable),
  data = agg_melt,
  stat = "identity" ,
  position = "fill"
) + scale_y_continuous(labels = percent) +labs(x="Category" , y= "Percentage (%)")

我已使用此代码尝试替换这些值,但它不起作用。

agg_melt %>%
  mutate(Percentage = value / sum(value)) %>%
  ggplot(aes(
    x = Category,
    y = Percentage,
    fill = `variable`,
    label = paste0(round(Percentage * 1000), "%")
  )) +
  geom_bar(position = "fill",
           color = "black" ,
           stat = "identity") +
  geom_text(position = position_fill(vjust = .5)) +
  scale_y_continuous(labels = scales::percent_format())

任何人都可以帮助为他们提供百分比标签吗? enter image description here

最佳答案

您可以在将结果传递给 ggplot 之前计算数据框中的百分比。

在这里,我假设您想要每个类别中的百分比(尽管如果您想要总体百分比,只需注释掉 group_by() 行):

library(dplyr)

agg_melt <- agg_melt %>%
  group_by(Category) %>%
  mutate(p = value / sum(value))

> head(agg_melt)
# A tibble: 6 x 4
# Groups: Category [4]
  Category variable value     p
  <fctr>   <fctr>   <dbl> <dbl>
1 1        IL1_Flag  21.0 0.208
2 2        IL1_Flag  17.0 0.215
3 3        IL1_Flag  16.0 0.211
4 4        IL1_Flag 219   0.211
5 1        IL2_Flag  20.0 0.198
6 2        IL2_Flag  17.0 0.215

将此修改后的数据帧传递给 ggplot。您还可以在顶级 ggplot() 中指定常见的美学参数,而不是在各个几何图形中指定:

ggplot(data = agg_melt,
       aes(y = value, 
           x = Category, 
           label = percent(p),
           fill = variable)) + 
  geom_col(position = "fill") + 
  geom_text(position = position_fill(vjust = 0.5)) +
  scale_y_continuous(labels = percent) +
  labs(x = "Category", 
       y = "Percentage (%)")

plot

关于r - 百分比标签到 100% 堆栈图尝试 "mutate"但不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48577500/

相关文章:

r - 根据另一个数据表的多个列值对一个数据表上的行进行子集化

r - ggplot 中的二进制列求和成百分比堆积条形图

r - ggplot2:将线宽应用于图例键

r - 在 ggplot2 中创建一个二类分级圆?

r - 总结 ggplot 用法的纬度、经度和计数数据

r - 如何使用ggplot2填充stat_poly_eq方程(ggpmisc)的背景?

xml - 将xml "rows"加载到R数据表中

r - 将生存数据从宽转换为长

r - 在 Shiny 的面板中绘制两个图形,一个图形在另一个图形下方

r - 更改 ggplot 填充