matplotlib条件格式标签

时间:2018-07-30 10:17:49

标签: python matplotlib

我有一个水平条形图,其中使用以下命令设置标签:

ax.set_yticklabels(df_chart.country_group)

我需要一些标签加粗(如果可能,请居中对齐),具体取决于标签的名称。

我尝试过:

ax.set_yticklabels(df_chart.country_group, weight=["bold", "bold", "normal"...])

,但是该函数不接受列表。 我也尝试过循环:

for label in ax.get_yticklabels():
     if label in ["World", "Developing countries", "Developed countries"]:
         label.set_fontproperties(weight="bold")

但是我无法从Text对象中提取标签值。

1 个答案:

答案 0 :(得分:1)

正确,您不能使用此类字体属性的列表。第二种方法是朝正确的方向发展。您需要从标签中get_text()与其他字符串进行比较。

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot([1,3,12])
ax.set_yticks([1,3,7,11])
ax.set_yticklabels(list("ABCD"))

for label in ax.get_yticklabels():
    if label.get_text() in ["B","C"]:
        label.set_weight("bold")

plt.show()

enter image description here

请注意,只有在这种情况下,如先前通过set_*ticklabels设置了标签文本,此功能才有效。

相关问题