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

如何将Matplotlib分组柱状图设置为灰度配色并添加区分图案?

实现灰度配色与图案填充的分组柱状图

你需要将现有分组柱状图改为灰度配色,并为每个系列添加可区分的填充图案,以下是修改后的完整代码及关键说明:

import matplotlib.pyplot as plt
import numpy as np

def plot_A2():
    fysiker = ("JB", "EG")

    volymer_A2 = {
        'M4': (22.9, 17.6), 
        'M5': (22.0, 16.4),
        'M6': (21.4, 16.0),
        'M7': (21.8, 17.6),
    }

    # 定义灰度色阶(从深到浅)和对应的填充图案
    grayscale_colors = ['#333333', '#666666', '#999999', '#cccccc']
    hatches = ['///', '\\\\\\', 'xxx', '+++']

    x = np.arange(len(fysiker))  # 标签位置
    width = 0.15  # 柱子宽度
    multiplier = -0.5

    fig, ax = plt.subplots(layout='constrained')

    # 循环时同时匹配颜色和图案
    for idx, (attribute, measurement) in enumerate(volymer_A2.items()):
        offset = width * multiplier
        # 应用灰度颜色与填充图案
        rects = ax.bar(x + offset, measurement, width, 
                       color=grayscale_colors[idx], 
                       hatch=hatches[idx],
                       label=attribute)
        ax.bar_label(rects, padding=3)
        multiplier += 1
  
    # 绘制真实体积参考线
    volume_A2 = 18.77
    ax.plot([-2,5], [volume_A2, volume_A2], "k--", linewidth=1, color='gray', label='True volume')

    # 图表基础设置
    ax.set_ylabel('Volume (ml)')
    ax.set_title('Phantom A2')
    ax.set_xticks(x + width, fysiker)
    ax.legend(loc='upper center')
    ax.set_ylim(15, 25)
    ax.set_xlim(-0.2, 1.5)

    plt.show()

plot_A2()

关键改动说明

  • 灰度配色定义:创建grayscale_colors列表,包含4种从深到浅的灰度值,对应4个数据系列
  • 填充图案设置:hatches列表定义4种差异化纹理(斜杠、反斜杠、叉号、加号),与灰度颜色一一绑定
  • 样式绑定:在ax.bar()中新增color和hatch参数,通过循环索引匹配对应样式,确保每个系列视觉区分度
  • 保留原有功能:完整保留原图表的标签、标题、坐标轴范围等设置,保证数据展示逻辑不变

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 05:50:02