我想知道製作y標籤的最佳方式,標籤中的每個單詞可以是不同的顏色。Matplotlib:多種顏色的y軸標籤
我想這樣做的原因是因爲我將製作包含曲線(電場和矢量勢場)的圖。這些曲線將是不同的顏色,我想在標籤中顯示。以下是一個簡化示例,使用以前的帖子(Matplotlib multiple colours in tick labels)來結束。這篇文章對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()
感謝您的幫助!
你有沒有想過使用'twinx()'?我通常在第二個y軸上繪製第二個數據集並相應地更改顏色 – Moritz