You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R的ggplot2创建带百分比的堆叠条形图、均值折线图及相似条形图

问题1:使用ggplot2创建带百分比数值的堆叠条形图及带百分比平均值的折线图

步骤1:加载依赖包并准备示例数据

library(ggplot2)
library(dplyr)

# 生成可复现的模拟数据
set.seed(123)
df <- data.frame(
  category = rep(c("A", "B", "C", "D"), each = 3),
  group = rep(c("X", "Y", "Z"), 4),
  value = sample(10:50, 12, replace = TRUE)
)

步骤2:计算百分比与分组平均值

先计算每个类别内各分组的占比,再统计每个分组的平均百分比:

# 计算类别内百分比
df_percent <- df %>%
  group_by(category) %>%
  mutate(percent = value / sum(value) * 100) %>%
  ungroup()

# 计算分组平均百分比
group_avg <- df_percent %>%
  group_by(group) %>%
  summarise(avg_percent = mean(percent)) %>%
  ungroup()

步骤3:绘制组合图表

通过双轴实现堆叠条形图与折线图的结合(注意双轴仅在数据逻辑匹配时使用):

p <- ggplot(df_percent, aes(x = category, y = percent, fill = group)) +
  # 堆叠条形图
  geom_col(position = "stack") +
  # 添加百分比标签(居中显示在条形内)
  geom_text(aes(label = sprintf("%.1f%%", percent)),
            position = position_stack(vjust = 0.5), size = 3) +
  # 添加平均值折线与点
  geom_line(data = group_avg, aes(x = category, y = avg_percent, group = 1, color = "平均百分比"),
            size = 1.2) +
  geom_point(data = group_avg, aes(x = category, y = avg_percent, color = "平均百分比"),
             size = 3) +
  # 样式调整
  scale_fill_brewer(palette = "Set2") +
  scale_color_manual(values = "#E64B35", name = "") +
  labs(title = "堆叠条形图+百分比平均值折线图",
       x = "类别", y = "百分比(%)") +
  theme_minimal() +
  theme(legend.position = "bottom")

print(p)

问题2:创建与目标样式相似的条形图

目标图特征:分组条形布局,每个主分组包含多个子类别条形,带误差线,条形上方标注数值,简洁经典主题。

步骤1:准备数据

library(ggplot2)
library(dplyr)

set.seed(456)
df_plot <- data.frame(
  group = rep(c("Group1", "Group2", "Group3"), each = 3),
  subgroup = rep(c("SubA", "SubB", "SubC"), 3),
  mean_val = sample(20:80, 9, replace = TRUE),
  se_val = runif(9, 2, 8) # 标准误,用于生成误差线
)

步骤2:绘制匹配样式的图表

p_similar <- ggplot(df_plot, aes(x = group, y = mean_val, fill = subgroup)) +
  # 分组条形,设置间距
  geom_col(position = position_dodge(width = 0.8), width = 0.7) +
  # 添加误差线
  geom_errorbar(aes(ymin = mean_val - se_val, ymax = mean_val + se_val),
                position = position_dodge(width = 0.8), width = 0.2) +
  # 添加数值标签(条形上方)
  geom_text(aes(label = mean_val),
            position = position_dodge(width = 0.8), vjust = -0.5, size = 3.5) +
  # 配色与主题调整
  scale_fill_manual(values = c("#619CFF", "#F8766D", "#00BA38")) +
  labs(title = "匹配样式的分组条形图",
       x = "分组", y = "数值") +
  theme_classic() +
  theme(legend.title = element_blank(),
        plot.title = element_text(hjust = 0.5),
        axis.text = element_text(size = 10),
        axis.title = element_text(size = 12))

print(p_similar)

内容的提问来源于stack exchange,提问作者MAS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 09:27:40