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

Python用Matplotlib绘制多直方图网格时为类别柱子设置独特色

Matplotlib多直方图网格图统一分类颜色实现方案

你可以预先定义全局统一的情感类别色值,在调用hist绘图方法时通过color参数传入即可。由于每个子图固定为3根柱子对应三类情感,传入的颜色列表会按顺序匹配柱子,所有子图共用同一套颜色列表就能保证同类型情感柱子颜色全局统一。

修改后的完整代码如下:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch

# 按柱子实际顺序配置色值,示例顺序为积极、中性、消极,可自行替换色值
EMOTION_COLORS = ['#2ecc71', '#f1c40f', '#e74c3c']
# 情感分类标签,用于生成图例,不需要可以删除
EMOTION_LABELS = ['积极', '中性', '消极']

def draw_histograms(df, variables, n_rows, n_cols):
    fig = plt.figure()
    for i, var_name in enumerate(variables):
        ax = fig.add_subplot(n_rows, n_cols, i+1)
        # 传入自定义颜色,edgecolor配置柱子边界为白色提升可读性
        df[var_name].hist(ax=ax, color=EMOTION_COLORS, edgecolor='white')
        ax.set_title(var_name)
        # 可选:为每个子图加统一图例,不需要可以删除以下两行
        legend_elements = [Patch(facecolor=EMOTION_COLORS[idx], label=EMOTION_LABELS[idx]) for idx in range(3)]
        ax.legend(handles=legend_elements)

    fig.tight_layout()
    fig.set_size_inches(20.5, 10.5)
    plt.show()

draw_histograms(df_final, df_final.columns, 2, 3)

如果实际柱子顺序和示例颜色顺序不匹配,直接调整EMOTION_COLORS列表内的色值顺序即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 23:06:06