设置matplotlib颜色栏范围

2024-09-28 16:23:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想设置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()

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


Tags: importnonedatamatplotlibasnpfigplt
3条回答

阿格。这是你最后一次尝试:

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

有效。

[抱歉,实际上是对弗吉尼亚州的红鳄鱼的一个回答,但没有足够的声誉发表评论]

我一直在更新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

Matplotlib 1.3.1-似乎只有在colorbar实例化时才会绘制colorbar记号。更改色条限制(set_clim)不会导致重新绘制记号。

我找到的解决方案是在与原始colorbar相同的轴条目中重新实例化colorbar。在本例中,轴[1]是原始颜色条。添加了colorbar的一个新实例,该实例使用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()

相关问题 更多 >