Skip to content Skip to sidebar Skip to footer

Changing Color Of Single Characters In Matplotlib Plot Labels

Using matplotlib in python 3.4: I would like to be able to set the color of single characters in axis labels. For example, the x-axis labels for a bar plot might be ['100','110','1

Solution 1:

It's going to involve a little work, I think. The problem is that individual Text objects have a single color. A workaround is to split your labels into multiple text objects.

First we write the last two characters of the label. To write the first character we need to know how far below the axis to draw -- this is accomplished using transformers and the example found here.

rlabsC = ['100','110','101','111']
xs = [1,2,3,4]
ys = [0,.5,.25,.25]

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.bar(xs,ys)
ax.set_xticks([a+.5 for a in xs])

plt.tick_params('x', labelbottom='off')

text_kwargs = dict(rotation='vertical', fontsize=16, va='top', ha='center')
offset = -0.02

for x, label in zip(ax.xaxis.get_ticklocs(), rlabsC):
    first, rest = label[0], label[1:]

    # plot the second and third numbers
    text = ax.text(x, offset, rest, **text_kwargs)

    # determine how far below the axis to place the first number
    text.draw(ax.figure.canvas.get_renderer())
    ex = text.get_window_extent()
    tr = transforms.offset_copy(text._transform, y=-ex.height, units='dots')

    # plot the first number
    ax.text(x, offset, first, transform=tr, color='red', **text_kwargs)

enter image description here

Post a Comment for "Changing Color Of Single Characters In Matplotlib Plot Labels"