Changing color of single characters in matplotlib plot labels

霸气de小男生 提交于 2021-01-29 02:40:25

问题


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!


回答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)



来源:https://stackoverflow.com/questions/33678606/changing-color-of-single-characters-in-matplotlib-plot-labels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!