【问题标题】:How to label colored bars on matplotlib? [duplicate]如何在 matplotlib 上标记彩色条? [复制]
【发布时间】:2021-04-04 18:03:29
【问题描述】:

我正在尝试绘制一个需要突出显示某些条形的条形图。如何包含说明彩色条是什么的图例?

下面是我的代码。我希望图例表明“相关条”是蓝色的(不是灰色,正如它目前所说的那样)。

import matplotlib.pyplot as plt

data = range(1,6)
labels = ['a','b','c','d','e']
relevant_bars = ['b','e']

bars = plt.bar(data, data, color='gray')

for i in range(len(bars)):
    if labels[i] in relevant_bars:
        bars[i].set_color('blue')

plt.xticks(pos, labels)
plt.legend(['Relevant bars']);

【问题讨论】:

标签: python matplotlib bar-chart


【解决方案1】:

改变

   plt.legend(['Relevant bars']);

    legend_elements = [Line2D([0], [0], color='b', lw=4, label='Relevant bars')]
    plt.legend(handles=legend_elements);

【讨论】:

    【解决方案2】:

    只需获取图例的矩形补丁并设置其颜色:

    legend = plt.legend(['Relevant bars'])
    legend.get_patches()[0].set_color('b')
    

    【讨论】:

      猜你喜欢
      • 2018-05-03
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多