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

如何用Pandas/Matplotlib为柱状图填充图案(适配黑白打印)

在Matplotlib/Pandas中给柱状图加填充图案(适配黑白打印)

完全可以实现你的需求!不管是用Pandas还是Matplotlib,都能给柱状条设置不同的填充图案,还能搭配颜色一起用,完美解决黑白打印后区分度的问题。下面我给你详细拆解操作方法:

核心:用hatch参数设置图案

Matplotlib的柱状图(bar方法)自带hatch参数,这就是用来设置填充图案的关键。常见的图案类型有这些:

  • /:斜杠线条
  • \:反斜杠线条
  • |:竖线
  • -:横线
  • +:十字交叉线
  • x:叉号交叉线
  • o:圆点填充
  • *:星号填充
    而且你还可以重复字符来调整图案密度,比如///就比/的线条更密,视觉效果更明显。

关于“图案调色板”

Matplotlib没有内置的现成图案调色板,但咱们可以自己定义一个图案列表,就像用颜色调色板那样循环使用,灵活度拉满。比如你可以提前定义好hatches = ["/", "\\", "x", "o", "+"],之后给不同柱子分配就行。

实操示例代码

基础单组柱状图(Pandas + Matplotlib)

假设你有一组简单的数据,咱们来实现带颜色+图案的柱状图:

import pandas as pd
import matplotlib.pyplot as plt

# 构造示例数据
df = pd.DataFrame({
    "产品类别": ["手机", "电脑", "平板", "耳机"],
    "销量": [1200, 850, 600, 980]
})

# 自定义颜色和图案列表(模拟调色板)
custom_colors = ["#4c72b0", "#dd8452", "#55a868", "#c44e52"]
custom_hatches = ["/", "\\", "x", "o"]

# 创建画布和轴对象
fig, ax = plt.subplots(figsize=(8, 5))

# 绘制柱状图
bars = ax.bar(df["产品类别"], df["销量"], color=custom_colors)

# 给每个柱子分配图案
for bar, hatch in zip(bars, custom_hatches):
    bar.set_hatch(hatch)

# 优化图表可读性
ax.set_xlabel("产品类别", fontsize=12)
ax.set_ylabel("月度销量", fontsize=12)
ax.set_title("产品销量柱状图(支持黑白打印)", fontsize=14)

plt.tight_layout()
plt.show()

进阶分组柱状图

如果是多组对比的柱状图,同样可以给每组设置专属图案:

import pandas as pd
import matplotlib.pyplot as plt

# 构造分组数据
df_group = pd.DataFrame({
    "产品类别": ["手机", "电脑", "平板", "耳机"],
    "线上销量": [800, 500, 350, 600],
    "线下销量": [400, 350, 250, 380]
}).set_index("产品类别")

# 自定义颜色和图案
colors = ["#4c72b0", "#dd8452"]
hatches = ["/", "x"]
bar_width = 0.35
x_pos = range(len(df_group.index))

# 创建画布
fig, ax = plt.subplots(figsize=(8, 5))

# 绘制两组柱状图
bars_online = ax.bar([x - bar_width/2 for x in x_pos], df_group["线上销量"], width=bar_width, color=colors[0])
bars_offline = ax.bar([x + bar_width/2 for x in x_pos], df_group["线下销量"], width=bar_width, color=colors[1])

# 设置图案
for bar in bars_online:
    bar.set_hatch(hatches[0])
for bar in bars_offline:
    bar.set_hatch(hatches[1])

# 完善图表信息
ax.set_xticks(x_pos)
ax.set_xticklabels(df_group.index)
ax.set_xlabel("产品类别", fontsize=12)
ax.set_ylabel("销量", fontsize=12)
ax.legend(["线上", "线下"], fontsize=10)
ax.set_title("线上VS线下销量对比", fontsize=14)

plt.tight_layout()
plt.show()

小Tips

  • 颜色和图案搭配时,尽量选择低饱和度的颜色,避免颜色太艳掩盖了图案,毕竟黑白打印时图案才是区分的核心
  • 如果用Pandas的df.plot.bar()方法,也可以先获取对应的ax对象,再通过ax.patches拿到所有柱子,然后逐个设置hatch参数,和上面的操作逻辑一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:21:22