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

ggplot基于已有按年份分组百分比数据绘制堆叠条形图咨询

解答

可视化方案适配性

  • 你要实现的每个年份下两个类别总高度100%的展示需求,完全可以用barplot实现,对应是百分比堆叠条形图,属于barplot的常用变体,非常适合展示不同年份下两类指标的占比变化。
  • 其他可选适配的可视化类型:
    • 百分比堆叠面积图:如果年份跨度大、数据点多,用面积图可以更顺滑的展示占比随时间的变化趋势
    • diverging条形图:如果需要更突出两个类别的占比差值,可以将0轴放在中间,一侧展示overRetail占比,另一侧展示belowRetail占比,差异对比会更直观

实现代码示例

Python (matplotlib)实现

import matplotlib.pyplot as plt
import numpy as np

# 替换为你自己的实际数据
years = ["2018", "2019", "2020", "2021", "2022"]
over_retail = [32, 41, 47, 49, 53]
below_retail = [68, 59, 53, 51, 47]

x_axis = np.arange(len(years))
bar_width = 0.6

# 绘制堆叠条形
plt.bar(x_axis, over_retail, bar_width, label="overRetail")
plt.bar(x_axis, below_retail, bar_width, bottom=over_retail, label="belowRetail")

# 图表配置
plt.xlabel("年份")
plt.ylabel("占比(%)")
plt.xticks(x_axis, years)
plt.ylim(0, 100)
plt.legend()

# 可选:添加占比文本标注
for idx in range(len(years)):
    plt.text(idx, over_retail[idx]/2, f"{over_retail[idx]}%", ha="center", va="center", color="white")
    plt.text(idx, over_retail[idx] + below_retail[idx]/2, f"{below_retail[idx]}%", ha="center", va="center", color="white")

plt.show()

R (ggplot2)实现

library(ggplot2)
library(tidyr)

# 替换为你的实际数据
df <- data.frame(
  year = c(2018, 2019, 2020, 2021, 2022),
  overRetail = c(32, 41, 47, 49, 53),
  belowRetail = c(68, 59, 53, 51, 47)
)

# 转换为长格式适配ggplot2绘图要求
df_long <- pivot_longer(df, cols = c(overRetail, belowRetail), names_to = "类别", values_to = "占比")

ggplot(df_long, aes(x = factor(year), y = 占比, fill = 类别)) +
  geom_col(position = "stack") +
  labs(x = "年份", y = "占比(%)") +
  scale_y_continuous(limits = c(0, 100)) +
  geom_text(aes(label = paste0(占比, "%")), position = position_stack(vjust = 0.5), color = "white") +
  theme_bw()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:15:05