【问题标题】:Changing color of single characters in matplotlib plot labels更改 matplotlib 绘图标签中单个字符的颜色
【发布时间】:2016-02-14 04:48:18
【问题描述】:

在 python 3.4 中使用 matplotlib:

我希望能够在轴标签中设置单个字符的颜色。

例如,条形图的 x 轴标签可能是 ['100','110','101','111',...],我希望第一个值是红色的,其他的都是黑色的。

这可能吗,有什么方法可以格式化文本字符串,以便以这种方式读出它们?也许有一些句柄可以在 set_xticklabels 上抓取并修改?

或者,除了 matplotlib 之外还有其他库可以做到吗?

示例代码(说明我的习惯用法):

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

谢谢!

【问题讨论】:

    标签: python python-3.x matplotlib


    【解决方案1】:

    我想这将涉及一些工作。问题是单个 Text 对象具有单一颜色。一种解决方法是将标签拆分为多个文本对象。

    首先我们写下标签的最后两个字符。要写第一个字符,我们需要知道要在轴下方绘制多远——这是使用转换器和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)
    

    【讨论】:

      猜你喜欢
      • 2013-09-08
      • 2011-08-30
      • 2011-06-13
      • 2020-12-26
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 2014-10-04
      相关资源
      最近更新 更多