Is it possible to have an tick labels formatted with different colours within the label
eg Using labels like this:
labels = ['apple - 1 : 7', 'orange - 5 : 10']
Such that the numbers 1 & 5 appear blue and 7 & 10 appear red?
Is it possible to have an tick labels formatted with different colours within the label
eg Using labels like this:
labels = ['apple - 1 : 7', 'orange - 5 : 10']
Such that the numbers 1 & 5 appear blue and 7 & 10 appear red?
如果您使用 matplotlib 的面向对象接口来绘制数据,您可以使用get_xticklabels和get_yticklabels访问每个轴的标签,然后更改您想要的颜色。
编辑:我误解了原来的问题。请参阅下文以获得更合适的答案。
一种可能性是删除原始标签并使用文本实例创建伪标签。这样,您可以在内部创建具有不同颜色的文本。这并不简单(您将不得不编写大量代码,特别是如果您有很多想要多色的标签),但下面是您可以做什么的示例。
这个想法是使用该方法以您想要的颜色创建每个标签的不同部分matplotlib.offsetbox.TextArea
,然后使用该方法将它们合并(我通过这篇文章matplotlib.offsetbox.HPacker
发现了 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()
这使: