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

如何使用Seaborn绘制含多变量的分季节堆叠条形图?

堆叠条形图绘制问题解决

数据集格式

Season  Phylum          Assigned    Yield
1   Acidobacteria       157363      High
1   Ignavibacteriae     15158       Low
1   Gemmatimonadetes    16408       High
2   Actinobacteria      143507      High
2   Chloroflexi         252391      Low
3   Cyanobacteria       172041      High
3   Firmicutes          74769       High
3   Acidobacteria       222991      Low
3   Bacteroidetes       280246      Low

当前尝试的代码

import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter, MultipleLocator
import seaborn as sns
import pandas as pd

df = pd.read_csv("./bacterial_phylum_abundance_root_allseasons.csv",sep='\t')
print(df)

sns.set_style('whitegrid')
g = sns.displot(data=df, x='Yield', hue='Phylum', col='Season', multiple='fill', shrink=0.7, palette='turbo')
g.set(xlabel='', ylabel='')
g.axes[0, 0].yaxis.set_major_locator(MultipleLocator(.1))
g.axes[0, 0].yaxis.set_major_formatter(PercentFormatter(1))
g.axes[0, 0].set_xlim(-.6, 1.6)
sns.despine(left=True)
plt.subplots_adjust(wspace=0)
plt.show()

问题说明

当前代码生成的图表不符合需求,期望绘制按季节分组、以Yield为X轴、Phylum为堆叠类别、Assigned值占比为高度的堆叠条形图,每个季节下对应High和Low两个条形,每个条形内部按Phylum堆叠展示占比。

解决方案

核心问题是误用了sns.displot(针对分布类图表),应改用sns.catplot配合堆叠条形配置,同时先预处理数据计算组内占比:

完整修正代码

import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter, MultipleLocator
import seaborn as sns
import pandas as pd

# 读取数据
df = pd.read_csv("./bacterial_phylum_abundance_root_allseasons.csv", sep='\t')

# 计算每个Season-Yield分组内,各Phylum的占比
df['percentage'] = df.groupby(['Season', 'Yield'])['Assigned'].transform(lambda x: x / x.sum())

sns.set_style('whitegrid')
# 绘制堆叠条形图
g = sns.catplot(
    data=df,
    x='Yield',
    y='percentage',
    hue='Phylum',
    col='Season',
    kind='bar',
    stacked=True,
    palette='turbo',
    shrink=0.7
)

# 统一设置所有子图的坐标轴格式
for ax in g.axes.flat:
    ax.yaxis.set_major_locator(MultipleLocator(.1))
    ax.yaxis.set_major_formatter(PercentFormatter(1))
    ax.set_xlabel('')
    ax.set_ylabel('')

sns.despine(left=True)
plt.subplots_adjust(wspace=0)
plt.show()

关键说明

  1. 数据预处理:通过groupby+transform计算分组内占比,这是堆叠占比图的核心前提;
  2. 图表类型替换:用catplot(kind='bar', stacked=True)替代displot,stacked=True开启堆叠模式,匹配需求;
  3. 坐标轴统一配置:遍历所有子图设置格式,避免仅修改第一个子图的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:20:43