是否可以在标签内设置使用不同颜色格式的刻度标签
例如,使用这样的标签:
labels = ['apple - 1 : 7', 'orange - 5 : 10']
Run Code Online (Sandbox Code Playgroud)
数字1和5显示为蓝色,7和10显示为红色?
如果使用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()
Run Code Online (Sandbox Code Playgroud)
这使:

| 归档时间: |
|
| 查看次数: |
1975 次 |
| 最近记录: |