如何用ggplot创建两个并排的堆叠条形图?
使用ggplot创建并排堆叠条形图
步骤1:整理数据
首先需要将两个数据框标准化格式,添加类别标签和区分类型的变量,再合并为一个数据框以便ggplot处理:
# 加载所需包 library(ggplot2) library(dplyr) # 原始数据框 lc2 <- structure(list(group = 1:3, sumpct = c(13, 32, 54)), class = "data.frame", row.names = c(NA, -3L)) le2 <- structure(list(e = 1:3, t = c(13, 38, 48)), class = "data.frame", row.names = c(NA, -3L)) # 处理点击可能性数据框 lc2_processed <- lc2 %>% mutate( # 添加类别标签 category = factor( c("极有可能/有些可能", "中立", "极不可能/有些不可能"), levels = c("极有可能/有些可能", "中立", "极不可能/有些不可能") ), # 添加类型标识 type = "点击可能性" ) %>% select(-group) # 移除无用列 # 处理报名可能性数据框 le2_processed <- le2 %>% mutate( category = factor( c("极有可能/有些可能", "中立", "极不可能/有些不可能"), levels = c("极有可能/有些可能", "中立", "极不可能/有些不可能") ), type = "报名可能性" ) %>% rename(sumpct = t) %>% # 统一列名 select(-e) # 合并数据框 combined_data <- rbind(lc2_processed, le2_processed)
步骤2:绘制堆叠条形图
使用ggplot绘制并排的堆叠条形图,同时添加百分比标签,还原目标效果:
ggplot(combined_data, aes(x = type, y = sumpct, fill = category)) + # 绘制堆叠条形 geom_col(position = "stack", width = 0.7) + # 添加每个堆叠部分的百分比标签 geom_text(aes(label = paste0(sumpct, "%")), position = position_stack(vjust = 0.5), size = 4, color = "white") + # 设置自定义颜色(可根据目标图调整) scale_fill_manual(values = c("#2E8B57", "#87CEEB", "#CD5C5C")) + # 设置坐标轴和标题 labs( x = "", y = "百分比", fill = "可能性分类", title = "点击与报名可能性分布" ) + # 调整主题样式 theme_minimal() + theme( plot.title = element_text(hjust = 0.5, size = 14, face = "bold"), legend.title = element_text(size = 12), legend.text = element_text(size = 10), axis.text = element_text(size = 11), axis.title.y = element_text(size = 12) )
效果说明
- 两个条形分别对应“点击可能性”和“报名可能性”,每个条形按“极有可能/有些可能”“中立”“极不可能/有些不可能”堆叠
- 每个堆叠块中间显示对应的百分比数值
- 可根据目标示例图的颜色调整
scale_fill_manual中的颜色值
内容的提问来源于stack exchange,提问作者Bruno Lizo
相关产品推荐
相关产品推荐

