如何使用matplotlib绘制带自定义双色条纹的水平条形图
双色条纹水平条形图实现方案
核心思路
通过matplotlib内置的条形填充图案(hatch)能力实现双色效果:先设置条形的基础填充色作为第一种颜色,再给条形添加自定义样式、自定义颜色的条纹作为第二种颜色。
完整可运行代码
import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.DataFrame({"P1_P2": [0.20], "P1_P3": [0.16], "P2_P5": [0.12], "P3_P5": [0.06], "P3_P6": [0.06], "P5_P6": [0.06]}) df=df.T fig, ax = plt.subplots(dpi=600, figsize=(4, 4), nrows=1, ncols=1, facecolor=None, edgecolor='black') # 绘制基础条形,设置第一种填充色 df.plot.barh(ax=ax, position=0.50, width=0.3, color=(245/255, 153/255, 145/255, 1.0)) ax.get_legend().remove() # 自定义条纹配置,可根据需求修改 stripe_color = (180/255, 40/255, 30/255) # 第二种条纹色,示例为深红色 stripe_style = '///' # 条纹样式:///斜纹、||竖纹、--横纹、xx交叉纹,符号越多条纹越密 stripe_width = 1.2 # 条纹粗细 # 给所有条形添加条纹 for bar in ax.patches: bar.set_hatch(stripe_style) bar.set_edgecolor(stripe_color) bar.set_linewidth(stripe_width) # 可选:如果需要条形外边框为黑色,取消下面代码的注释即可 # outer_border = plt.Rectangle((bar.get_x(), bar.get_y()), bar.get_width(), bar.get_height(), # fill=False, edgecolor='black', linewidth=0.5) # ax.add_patch(outer_border) plt.show()
参数调整说明
- 替换
stripe_color的RGB值即可自定义第二种条纹的颜色 - 调整
stripe_style的符号和数量可以修改条纹的方向和密度,比如'//'是稀疏斜纹,'////'是高密度斜纹 - 修改
stripe_width的数值可以调整条纹线条的粗细
内容的提问来源于stack exchange,提问作者Matthi9000
相关产品推荐
相关产品推荐

