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

使用Seaborn绘制按周统计的病毒占比堆叠条形图需求

使用Seaborn绘制带百分比标签的堆叠条形图

要实现每周病毒占比的堆叠条形图,我们需要先预处理数据计算百分比,再结合Seaborn和Matplotlib完成绘图,具体步骤如下:

1. 数据预处理

首先计算每周各病毒的出现次数,再转换为该周的占比百分比:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# 加载原始数据
data = {'Week': [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2],
        'Virus': ['A', 'B', 'C', 'A', 'B', 'C', 'B', 'C', 'A', 'D', 'A', 'A', 'C', 'D', 'B', 'C', 'D', 'B']}
df = pd.DataFrame(data)

# 统计每周各病毒的数量
count_df = df.groupby(['Week', 'Virus']).size().unstack(fill_value=0)
# 转换为每周的占比百分比
percent_df = count_df.div(count_df.sum(axis=1), axis=0) * 100

2. 绘制堆叠条形图

Seaborn没有原生的堆叠条形图函数,我们可以结合Matplotlib实现堆叠,并使用Seaborn的配色系统:

# 设置Seaborn绘图风格
sns.set_style("whitegrid")

# 获取所有病毒类别,分配专属颜色
virus_categories = percent_df.columns
custom_colors = sns.color_palette("husl", n_colors=len(virus_categories))

# 创建画布和坐标轴
fig, ax = plt.subplots(figsize=(10, 6))

# 初始化堆叠的底部位置
bottom_pos = pd.Series([0]*len(percent_df.index), index=percent_df.index)

# 逐个绘制每个病毒的堆叠条形,并添加百分比标签
for virus, color in zip(virus_categories, custom_colors):
    # 绘制条形
    ax.bar(percent_df.index, percent_df[virus], bottom=bottom_pos, label=virus, color=color)
    # 添加百分比标签(仅显示非零值)
    for week, percentage in zip(percent_df.index, percent_df[virus]):
        if percentage > 0:
            ax.text(week, bottom_pos[week] + percentage/2, f'{percentage:.1f}%', 
                    ha='center', va='center', fontsize=10)
    # 更新堆叠底部位置
    bottom_pos += percent_df[virus]

# 设置图表元素
ax.set_xlabel('Week', fontsize=12)
ax.set_ylabel('Percentage (%)', fontsize=12)
ax.set_title('Weekly Virus Proportion', fontsize=14)
ax.set_xticks(percent_df.index)
ax.legend(title='Virus', bbox_to_anchor=(1.05, 1), loc='upper left')

# 调整布局,避免标签被截断
plt.tight_layout()
plt.show()

效果说明

  • 每个条形代表一周的数据,不同颜色对应不同病毒
  • 条形内部的标签显示该病毒在当周的占比百分比
  • 使用Seaborn的husl配色方案,确保每个病毒的颜色区分度高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:45:33