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

Python使用循环批量绘制TS1-TS5列分类计数柱状图,简化重复代码

简化实现代码

你可以通过循环遍历需要绘制的列、对应标题和子图位置的映射关系来消除重复代码,适配你当前的Python2.7 + pandas 0.24.2环境,且能保证原本的排序要求:

from pandas.api.types import CategoricalDtype
import seaborn as sns
import matplotlib.pyplot as plt

# 原有基础代码保留
num_range = list(range(110,140, 2))
OUTCOMES = ['NOT_SEEN', 'NOT_ABLE', 'HIGH_BAR']
OUTCOMES.extend([str(num) for num in num_range])
OUTCOMES = CategoricalDtype(OUTCOMES, ordered = True)

fig, ax =plt.subplots(2, 3, sharey=True)
fig.tight_layout(pad=3)

# 定义所有需要绘制的列对应信息:(列名, 图表标题, 子图位置)
plot_list = [
    ("TS1", "Testing 1", ax[0,0]),
    ("TS2", "Testing 2", ax[0,1]),
    ("TS3", "Testing 3", ax[0,2]),
    ("TS4", "Testing 4", ax[1,0]),
    ("TS5", "Testing 5", ax[1,1]),
]

# 循环执行绘制逻辑
for col_name, title, cur_ax in plot_list:
    df["outcomes"] = df[col_name].astype(OUTCOMES)
    bpt = sns.countplot(x="outcomes", data=df, palette='GnBu', ax=cur_ax)
    plt.setp(bpt.get_xticklabels(), rotation=60, size=6, ha='right')
    bpt.set(xlabel='')
    bpt.set_title(title)

# 原有收尾代码保留
ax[1,2].set_visible(False)
plt.show()

说明

  1. 你提前定义的OUTCOMES是有序分类类型,已经按照要求的顺序配置,astype转换后seaborn的countplot会自动按照分类顺序绘制柱子,不需要额外调整排序逻辑。
  2. 数据中超出你定义范围的取值(如样例中的145、180)转换后会变为NaN,countplot默认不会统计,符合你的统计规则。
  3. 后续如果需要新增/修改绘制的列,只需要调整plot_list中的配置即可,不需要重复复制绘制代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:48:03