python matplotlib colorbar设置tick formator / locator更改刻度标签

时间:2011-06-26 15:54:42

标签: python matplotlib customization colorbar

用户, 我想自定义颜色条上的刻度线。但是,我发现了以下奇怪的行为。我尝试将tick formator更改为默认格式(我认为这应该什么都不改变)但我最终得到了不同的标签。有谁知道我做错了什么?或者这是一个错误吗?

我使用git的matplotlib(v1.0.1-961-gb516ae0,git describe)。 以下代码生成两个图:

#http://matplotlib.sourceforge.net/examples/pylab_examples/griddata_demo.html
from numpy.random import uniform, seed
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np
# make up data.
seed(0)
npts = 200
x = uniform(-2,2,npts)
y = uniform(-2,2,npts)
z = x*np.exp(-x**2-y**2)
# define grid
xi = np.linspace(-2.1,2.1,100)
yi = np.linspace(-2.1,2.1,200)
# grid the data.
zi = griddata(x,y,z,xi,yi,interp='linear')

##### FIRST PLOT
plt.figure()
CS  = plt.contour(xi,yi,zi,25,cmap=plt.cm.jet)
bar = plt.colorbar() # draw colorbar
# plot data points.
#plt.scatter(x,y,marker='o',c='b',s=5,zorder=10)
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.title('griddata test (%d points)' % npts)
plt.show()

##### SECOND PLOT
plt.figure()
CS  = plt.contour(xi,yi,zi,25,cmap=plt.cm.jet)
bar = plt.colorbar() # draw colorbar
bar.ax.yaxis.set_minor_locator(matplotlib.ticker.AutoLocator())
bar.ax.yaxis.set_major_locator(matplotlib.ticker.AutoLocator())
# plot data points.
#plt.scatter(x,y,marker='o',c='b',s=5,zorder=10)
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.title('griddata test (%d points)' % npts)
plt.show()

1 个答案:

答案 0 :(得分:16)

我刚刚找到了解决方案。一个人必须致电

bar.update_ticks()

更改格式化程序/定位器后,请参阅

http://matplotlib.sourceforge.net/api/colorbar_api.html

然后一切顺利。

更新

这也是更改Formator / Locator的代码。它基于colorbar-code的内部结构,所以也许其他人有更好的解决方案:

#http://matplotlib.sourceforge.net/examples/pylab_examples/griddata_demo.html
from numpy.random import uniform, seed
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np
# make up data.
seed(0)
npts = 200
x = uniform(-2,2,npts)
y = uniform(-2,2,npts)
z = x*np.exp(-x**2-y**2)
# define grid
xi = np.linspace(-2.1,2.1,100)
yi = np.linspace(-2.1,2.1,200)
# grid the data.
zi = griddata(x,y,z,xi,yi,interp='linear')

##### PLOT
plt.figure()
CS  = plt.contour(xi,yi,zi,25,cmap=plt.cm.jet)
bar = plt.colorbar(orientation='horizontal') # draw colorbar


tick_locs   = [-3.9e-1,-2.6e-1,-1.3e-1,0e-1,1.3e-1,2.6e-1,3.9e-1]
tick_labels = ['-0.390','-0.260','-0.130','0','0.13','0.26','0.390']


bar.locator     = matplotlib.ticker.FixedLocator(tick_locs)
bar.formatter   = matplotlib.ticker.FixedFormatter(tick_labels)
bar.update_ticks()

# plot data points.
#plt.scatter(x,y,marker='o',c='b',s=5,zorder=10)
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.title('griddata test (%d points)' % npts)
plt.show()