首页 > 解决方案 > 使用字符数据的百分比堆积条形图

问题描述

假设我有这些数据:

dat <- read.table(text = " name1 name2
jim bob
jim bob
jim tom
jim sue
jim other
sue bob
sue tom
sue jim
bob bob
bob jim
bob bob
bob sue
bob jim
bob other
bob other",sep = "",header = TRUE)

如何使用 ggplot2 制作堆积条形图?我想name1在 x 轴上,每个百分比name2在 y 轴上。因此,对于jim,它将bobtom0.4、0.2、0.2sueother0.2。

标签: rggplot2plotgraphcharts

解决方案


使用dplyr,我们可以计算每个name2in的比率name1并使用 绘制它们ggplot

library(dplyr)
library(ggplot2)

dat %>%
  group_by(name1, name2) %>%
  summarise(n = n()) %>%
  mutate(n = n/sum(n)) %>%
  ggplot() + aes(name1, n,  fill = name2, label = round(n, 2)) +
  geom_col() + 
  geom_text(size = 3, position = position_stack(vjust = 0.5))

在此处输入图像描述


推荐阅读