【问题标题】:Change colour/font-weight of axis label if it belongs in a list如果轴标签属于列表,则更改其颜色/字体粗细
【发布时间】:2017-06-21 05:51:18
【问题描述】:

所以我正在创建一个包含很多条目的条形图。在 y 轴上,它只显示 x 轴上的任何标签/条目的值。所以总而言之,我得到了很多不同高度的酒吧 - 应该是这样。

现在,一些 x 轴标签/条目比其他的更重要。所以我创建了一个包含所有重要标签/条目的列表。我现在的想法是,我想更改列表中包含的那些标签/条目的颜色或字体粗细(使它们变粗)。但我真的不知道该怎么做。

我现在使用的情节代码只是:

plt.bar(indexes, values, width, color="#3F5D7D", edgecolor="#111111", align='center')
plt.xticks(indexes, labels, fontsize=10, rotation='vertical')
plt.xlim([-0.5,indexes.size-0.5])
plt.subplots_adjust(left=0.05, bottom=0.20, right=0.95, top=0.95, wspace=0.2, hspace=0.2)
plt.show()

其中indexes 是每个标签/条目的索引,values 当然是它们的值,在plt.xticks 中我只是将indexes 更改为labels

然后我有一个标签列表,我们称之为main_labels = ['important_label1', 'important_label2', 'important_label3'...] 等等。是的,现在我想要它,所以当标签是这个 main_labels 列表的一部分时,它会变成粗体或其他颜色。

【问题讨论】:

    标签: python matplotlib label bar-chart


    【解决方案1】:

    您可以遍历main_labels,找出标签在labels列表中的位置并更改相应的刻度标签。

    import matplotlib.pyplot as plt
    indexes = [1,2,3,5,6]
    values = [8,6,4,5,3]
    width = 0.8
    labels = ["cow","ox","pig","dear","bird"]
    main_labels = ["ox", "pig", "bird"]
    
    
    plt.bar(indexes, values, width, color="#3F5D7D", edgecolor="#111111", align='center')
    plt.xticks(indexes, labels, fontsize=10, rotation='vertical')
    plt.xlim([0.5,max(indexes)+0.5])
    plt.subplots_adjust(left=0.05, bottom=0.20, right=0.95, top=0.95, wspace=0.2, hspace=0.2)
    
    ticklabels = [t for t in plt.gca().get_xticklabels()]
    for l in main_labels:
        i = labels.index(l)
        ticklabels[i].set_color("red")
        ticklabels[i].set_fontweight("bold")
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 2013-07-24
      • 2014-07-16
      • 1970-01-01
      相关资源
      最近更新 更多