1

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','101','111',...], and I would like the first value to be red, and the others black.

Is this possible, is there some way I could format the text strings so that they would be read out in this way? Perhaps there is some handle that can be grabbed at set_xticklabels and modified?

or, is there some library other than matplotlib that could do it?

example code (to give an idea of my idiom):

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])
ax.set_xticklabels(rlabsC, fontsize=16, rotation='vertical')

thanks!

Morgan Thrapp
  • 9,748
  • 3
  • 46
  • 67
Andrew
  • 13
  • 3

1 Answers1

0

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

jme
  • 19,895
  • 6
  • 41
  • 39