[英]Changing color of single characters in matplotlib plot labels
在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')
謝謝!
我認為這將涉及一些工作。 問題在於各個Text
對象只有一種顏色。 一種解決方法是將標簽拆分為多個文本對象。
首先,我們寫標簽的最后兩個字符。 要編寫第一個字符,我們需要知道要繪制的軸下方有多遠-這是使用變壓器和此處找到的示例完成的。
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.