Skip to content Skip to sidebar Skip to footer

Matplotlib Multiple Colours In Tick Labels

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 numb

Solution 1:

If you are using the object-oriented interface of matplotlib to plot your data, you can use the get_xticklabels and get_yticklabels to access the labels of each axis and then change the color of the ones you want.

EDIT : I misunderstood the original question. See below for a more appropriate answer.

One of the possibility is to remove the original labels and create pseudo-labels using a text instance. This way, you can create text with different color inside. It is not straightforwad (you will have to write a lot of code, especially if you have a lot of labels you want to multi-colorize), but below is an example of what you can do.

The idea is to create the different parts of each label in the color you want using the matplotlib.offsetbox.TextArea method, and then merge them using the matplotlib.offsetbox.HPacker method (I discovered the HPacker method via this post).

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()

Which gives:

appleorange

Post a Comment for "Matplotlib Multiple Colours In Tick Labels"