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

如何获取柱状图颜色并匹配对应参考线颜色

解决参考线颜色与柱状图颜色匹配的问题

要让参考线颜色和对应柱状图的颜色完全一致,你可以直接从绘制好的柱状图中提取对应系列的颜色,再将其应用到参考线上。以下是修改后的代码:

import pandas as pd
import matplotlib.pyplot as plt

data = {'CCM1': {'Exact': 15.32, '1 Notch': 36.29, '2 Notches': 45.97},
    'CCM2': {'Exact': 24.19, '1 Notch': 42.74, '2 Notches': 54.03},
    'CCM3': {'Exact': 39.25, '1 Notch': 70.09, '2 Notches': 88.79},
    'CCM4': {'Exact': 29.03, '1 Notch': 65.32, '2 Notches': 88.71},
    'CCQ1': {'Exact': 17.74, '1 Notch': 41.40, '2 Notches': 54.84},
    'CCQ2': {'Exact': 25.27, '1 Notch': 50, '2 Notches': 64.52},
    'CCQ3': {'Exact': 29.57, '1 Notch': 67.74, '2 Notches': 89.25},
    'CCQ4': {'Exact': 31.18, '1 Notch': 67.74, '2 Notches': 88.71},
    'PCM1': {'Exact': 15.05, '1 Notch': 30.65, '2 Notches': 42.47},
    'PCM2': {'Exact': 15.05, '1 Notch': 28.49, '2 Notches': 42.47},
    'PCM3': {'Exact': 22.58, '1 Notch': 44.09, '2 Notches': 64.52},
    'PCM4': {'Exact': 40.32, '1 Notch': 68.28, '2 Notches': 84.95},
    'PCQ1': {'Exact': 12.37, '1 Notch': 26.34, '2 Notches': 32.36},
    'PCQ2': {'Exact': 11.83, '1 Notch': 29.57, '2 Notches': 46.24},
    'PCQ3': {'Exact': 34.41, '1 Notch': 64.52, '2 Notches': 86.02},}

df = pd.DataFrame(data)
df = df.T
df['sum'] = df.sum(axis=1)
sorted_df = df.sort_values('sum', ascending=False)[['Exact','1 Notch','2 Notches']]
ax = sorted_df.plot.bar() 

# 提取三个柱状系列对应的颜色
num_groups = len(sorted_df)
# 每个系列的第一个柱状条分别在索引0、num_groups、num_groups*2的位置
colors = [ax.patches[i].get_facecolor() for i in [0, num_groups, num_groups*2]]

# 使用提取的颜色绘制参考线
plt.axhline(y=31.75, color=colors[0], linestyle='--')
plt.axhline(y=76.19, color=colors[1], linestyle='--')
plt.axhline(y=90.48, color=colors[2], linestyle='--')

plt.show()

说明:

  1. 绘制柱状图后,通过ax.patches获取所有柱状条的对象,每个柱状条的颜色可以用get_facecolor()方法获取。
  2. 分组柱状图中,同一系列(如Exact)的所有柱状条颜色相同,因此只需取每个系列的第一个柱状条颜色即可。
  3. 按照指定的参考线数值,将对应系列的颜色赋值给参考线,就能实现颜色完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 18:50:36