操作颜色条上的刻度标签 [英] manipulate tick labels on a colorbar
问题描述
我想访问matplotlib colobar上的刻度标签,以便可以操作它们.
例如,我的起始标签可能是 [-2,-1,0,1,2].
我用过:
locs,oldlabels = plt.xticks()newlabels = ['a','b','c','d','e']plt.xticks(locs, newlabels)
这有效.但是我不想手动写新标签.我想访问旧标签,以便我可以将新标签设为 [2*(-2), 2*(-1), 2*0, 2*1, 2*2].
我只是不知道如何获取"旧标签.我搜索了所有内容,并尝试了很多方法,但我所做的事情根本上是错误的.
我试图打印 oldlabels[0],但我得到了 Text(0,0,u'\u22122.0').
<小时>我目前正在做
new_labels = [1,2,3,4,5,6,7,8,9]colorbarname.ax.set_xticklabels(new_labels)
有效.但我想将它们设置为旧值的 2 倍.如何自动执行此操作?我需要提取旧标签值,乘以(比如说)2,用新值更新轴标签.
如果您的数据不限于[0,1],建议您在将数据传递到颜色表时使用规范,而不要更改数据并重新标记颜色条:
I want to access the tick labels on my matplotlib colobar, so that I can manipulate them.
My starting labels may be [-2,-1,0,1,2] for example.
I have used:
locs,oldlabels = plt.xticks()
newlabels = ['a','b','c','d','e']
plt.xticks(locs, newlabels)
This works. But I don't want to manually write in the new labels. I want to access the oldlabels, so that I can have the newlabels as say [2*(-2), 2*(-1), 2*0, 2*1, 2*2].
I just don't know how to 'get at' the oldlabels. I googled everything and tried lots of things, but I'm doing something fundamentally wrong.
I tried to print oldlabels[0], but I get Text(0,0,u'\u22122.0').
EDIT:
I'm currently doing:
new_labels = [1,2,3,4,5,6,7,8,9]
colorbarname.ax.set_xticklabels(new_labels)
which works. But I want to set them as 2 x their old value. How can I do this automatically? I need to extract the old label values, multiply by (say) 2, update the axis labels with the new values.
If your data is not confined to [0,1], I'd recommend using a norm when you pass the data to the colormap instead of changing the data and relabeling the colorbar: http://matplotlib.org/api/cm_api.html?highlight=norm%20colormap#matplotlib.cm.ScalarMappable.norm
However, you can relabel the colorbar by manipulating the underlying axis directly:
import numpy as np
import pylab as plt
A = np.random.random((10,10))
plt.subplot(121)
plt.imshow(A,interpolation='nearest')
cb = plt.colorbar()
oldlabels = cb.ax.get_yticklabels()
print(map(lambda x: x.get_text(),oldlabels))
newlabels = map(lambda x: str(2 * float(x.get_text())), oldlabels)
print(newlabels)
cb.ax.set_yticklabels(newlabels)
plt.show()
oh, and now I find the matplotlib gallery example, nearly the same: http://matplotlib.org/examples/pylab_examples/colorbar_tick_labelling_demo.html
这篇关于操作颜色条上的刻度标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!