ラベル内で異なる色でフォーマットされた目盛りラベルを持つことは可能ですか?
例:次のようなラベルの使用:
labels = ['apple - 1 : 7', 'orange - 5 : 10']
1と5の数字が青で表示され、7と10の数字が赤で表示されるように?
ラベル内で異なる色でフォーマットされた目盛りラベルを持つことは可能ですか?
例:次のようなラベルの使用:
labels = ['apple - 1 : 7', 'orange - 5 : 10']
1と5の数字が青で表示され、7と10の数字が赤で表示されるように?
matplotlib のオブジェクト指向インターフェイスを使用してデータをプロットしている場合は、get_xticklabelsとget_yticklabelsを使用して各軸のラベルにアクセスし、必要な色を変更できます。
編集:元の質問を誤解しました。より適切な回答については、以下を参照してください。
可能性の 1 つは、元のラベルを削除し、テキスト インスタンスを使用して疑似ラベルを作成することです。このようにして、内部に異なる色のテキストを作成できます。これは単純ではありません (特に多色にしたいラベルがたくさんある場合は、多くのコードを書く必要があります) が、以下はできることの例です。
アイデアは、メソッドを使用して必要な色で各ラベルのさまざまな部分を作成し、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()
これにより、次のことが得られます。