简体   繁体   English

更改matplotlib图标签中单个字符的颜色

[英]Changing color of single characters in matplotlib plot labels

Using matplotlib in python 3.4: 在python 3.4中使用matplotlib:

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. 例如,条形图的x轴标签可能是['100','110','101','111',...],我希望第一个值为红色,而其他值黑色。

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? 也许有一些可以在set_xticklabels处进行抓取并修改的句柄?

or, is there some library other than matplotlib that could do it? 或者,除了matplotlib之外,还有其他库可以做到吗?

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! 谢谢!

It's going to involve a little work, I think. 我认为这将涉及一些工作。 The problem is that individual Text objects have a single color. 问题在于各个Text对象只有一种颜色。 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)

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM