Matplotlib刻度标签中的多种颜色

时间:2012-07-04 09:00:39

标签: python matplotlib

是否可以在标签

中使用不同颜色格式化刻度标签

例如使用这样的标签:

labels = ['apple - 1 : 7', 'orange - 5 : 10']

这样的数字1& 5显示蓝色和7& 10出现红色?

1 个答案:

答案 0 :(得分:5)

如果您使用matplotlib的面向对象的界面来绘制数据,您可以使用get_xticklabelsget_yticklabels访问每个轴的标签,然后更改您的颜色想。

编辑:我误解了原来的问题。请参阅下面的更合适的答案。

其中一种可能性是删除原始标签并使用文本实例创建伪标签。这样,您可以在里面创建不同颜色的文本。它不是直接的(你必须编写很多代码,特别是如果你有很多你想要多色的标签),但下面是你可以做的一个例子。

我们的想法是使用matplotlib.offsetbox.TextArea方法以您想要的颜色创建每个标签的不同部分,然后使用matplotlib.offsetbox.HPacker方法合并它们(我通过{{3发现了HPacker方法}})。

import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, HPacker

fig = plt.subplots(1)

ax.bar([0, 1], [20, 35], 0.35, color='0.5', yerr=[2, 3], ecolor='k')
ax.set_xlim([-0.2, 1.7])
ax.set_xticks([]) # empty xticklabels

# apple label
abox1 = TextArea("apple - ", textprops=dict(color="k", size=15))
abox2 = TextArea("1 ", textprops=dict(color="b", size=15))
abox3 = TextArea(": ", textprops=dict(color="k", size=15))
abox4 = TextArea("7 ", textprops=dict(color="r", size=15))

applebox = HPacker(children=[abox1, abox2, abox3, abox4],
                  align="center", pad=0, sep=5)

# orange label
obox1 = TextArea("orange - ", textprops=dict(color="k", size=15))
obox2 = TextArea("5 ", textprops=dict(color="b", size=15))
obox3 = TextArea(": ", textprops=dict(color="k", size=15))
obox4 = TextArea("10 ", textprops=dict(color="r", size=15))

orangebox = HPacker(children=[obox1, obox2, obox3, obox4],
                    align="center", pad=0, sep=5)

anchored_applebox = AnchoredOffsetbox(loc=3, child=applebox, pad=0., frameon=False,
                                      bbox_to_anchor=(0.1, -0.07),
                                      bbox_transform=ax.transAxes, borderpad=0.)

anchored_orangebox = AnchoredOffsetbox(loc=3, child=orangebox, pad=0., frameon=False,
                                       bbox_to_anchor=(0.6, -0.07),
                                       bbox_transform=ax.transAxes, borderpad=0.)

ax.add_artist(anchored_applebox)
ax.add_artist(anchored_orangebox)

plt.show()

给出了:

appleorange