我想知道什么是最好的方式来做一个y标签,其中每个字在标签可以是不同的颜色。
我之所以喜欢这个是因为我将绘制包含到曲线(电场和矢量势场)的图。这些曲线将是不同的颜色,我想显示在标签上。下面是一个简单的示例,使用前面的post(Matplotlib multiple colours in tick labels)来接近。这个post对于x轴很好,但是它不能正确地对y轴进行空间/顺序排列。
另一篇文章有一个类似的问题(Partial coloring of text in matplotlib),但是第一个答案似乎不再起作用,第二个答案使您将文件保存为.ps文件。
我的示例代码是
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, HPacker, VPacker
ax = plt.subplot(111)
x = np.linspace(0,10,10)
y1 = x
y2 = x**2
ax.plot(x,y1,color='r',label='data1')
ax.plot(x,y2,color='b',label='data2')
ax.set_xticks([]) # empty xticklabels
ax.set_yticks([]) # empty xticklabels
# x-axis label
xbox1 = TextArea("Data1-x ", textprops=dict(color="r", size=15))
xbox2 = TextArea("and ", textprops=dict(color="k", size=15))
xbox3 = TextArea("Data2-x ", textprops=dict(color="b", size=15))
xbox = HPacker(children=[xbox1, xbox2, xbox3],
align="center", pad=0, sep=5)
anchored_xbox = AnchoredOffsetbox(loc=3, child=xbox, pad=0., frameon=False,
bbox_to_anchor=(0.3, -0.07),
bbox_transform=ax.transAxes, borderpad=0.)
# y-axis label
ybox1 = TextArea("Data1-y ", textprops=dict(color="r", size=15,rotation='vertical'))
ybox2 = TextArea("and ", textprops=dict(color="k", size=15,rotation='vertical'))
ybox3 = TextArea("Data2-y ", textprops=dict(color="b", size=15,rotation='vertical'))
ybox = VPacker(children=[ybox1, ybox2, ybox3],
align="center", pad=0, sep=5)
anchored_ybox = AnchoredOffsetbox(loc=8, child=ybox, pad=0., frameon=False,
bbox_to_anchor=(-0.08, 0.4),
bbox_transform=ax.transAxes, borderpad=0.)
ax.add_artist(anchored_xbox)
ax.add_artist(anchored_ybox)
plt.legend()
plt.show()
谢谢你的帮助!
你就快到了。您只需要使用ha='left',va='bottom'指定文本的对齐方式。(并翻转传递给VPacker的TextArea对象的顺序)。
更好的是,这里有一个函数,它使标签使用字符串和颜色的任意列表:
它仍然需要在“bbox_to_anchor”关键字中对位置进行一些修改。
相关问题 更多 >
编程相关推荐