25

我想设置 matplotlib 颜色条范围。这是我到目前为止所拥有的:

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(20)
y = np.arange(20)
data = x[:-1,None]+y[None,:-1]

fig = plt.gcf()
ax = fig.add_subplot(111)

X,Y = np.meshgrid(x,y)
quadmesh = ax.pcolormesh(X,Y,data)
plt.colorbar(quadmesh)

#RuntimeError: You must first define an image, eg with imshow
#plt.clim(vmin=0,vmax=15)  

#AttributeError: 'AxesSubplot' object has no attribute 'clim'
#ax.clim(vmin=0,vmax=15) 

#AttributeError: 'AxesSubplot' object has no attribute 'set_clim'
#ax.set_clim(vmin=0,vmax=15) 

plt.show()

如何在此处设置颜色条限制?

4

3 回答 3

35

精氨酸。它总是你尝试的最后一件事:

quadmesh.set_clim(vmin=0, vmax=15)

作品。

于 2013-03-07T21:35:22.650 回答
4

Matplotlib 1.3.1 - 看起来颜色条刻度仅在颜色条被实例化时才绘制。更改颜色条限制 (set_clim) 不会导致重新绘制刻度。

我找到的解决方案是在与原始颜色条相同的轴条目中重新实例化颜色条。在这种情况下,axes[1] 是原始颜色条。添加了一个新的颜色条实例,该实例使用 cax=(子轴)kwarg 指定。

           # Reset the Z-axis limits
           print "resetting Z-axis plot limits", self.zmin, self.zmax
           self.cbar = self.fig.colorbar(CS1, cax=self.fig.axes[1]) # added
           self.cbar.set_clim(self.zmin, self.zmax)
           self.cbar.draw_all()
于 2015-01-26T19:08:18.290 回答
4

[对不起,实际上是弗吉尼亚州对 The Red Gator 的评论,但没有足够的声誉来评论]

在绘制imshow 对象,我一直在更新它的颜色条,并且数据使用 imshowobj.set_data() 进行了更改。使用 cbarobj.set_clim() 确实会更新颜色,但不会更新颜色条的刻度或范围。相反,您必须使用 imshowobj.set_clim() 来正确更新图像和颜色条。

data = np.cumsum(np.ones((10,15)),0)
imshowobj = plt.imshow(data)
cbarobj = plt.colorbar(imshowobj) #adjusts scale to value range, looks OK
# change the data to some data with different value range:
imshowobj.set_data(data/10) #scale is wrong now, shows only dark color
# update colorbar correctly using imshowobj not cbarobj:
#cbarobj.set_clim(0,1) #! image colors will update, but cbar ticks not
imshowobj.set_clim(0,1) #correct
于 2018-05-27T10:01:14.047 回答