mgilson
mgilson

Reputation: 309831

Setting matplotlib colorbar range

I would like to set the matplotlib colorbar range. Here's what I have so far:

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()

How do I set the colorbar limits here?

Upvotes: 26

Views: 73531

Answers (3)

ldoyle
ldoyle

Reputation: 41

[Sorry, actually a comment to The Red Gator in Virginias answer, but do not have enough reputation to comment]

I was stuck on updating the colorbar of an imshow object after it was drawn and the data changed with imshowobj.set_data(). Using cbarobj.set_clim() indeed updates the colors, but not the ticks or range of the colorbar. Instead, you have to use imshowobj.set_clim() which will update the image and colorbar correctly.

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

Upvotes: 4

mgilson
mgilson

Reputation: 309831

Arg. It's always the last thing you try:

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

works.

Upvotes: 40

Matplotlib 1.3.1 - It looks like the colorbar ticks are only drawn when the colorbar is instanced. Changing the colorbar limits (set_clim) does not cause the ticks to be re-drawn.

The solution I found was to re-instance the colorbar in the same axes entry as the original colorbar. In this case, axes[1] was the original colorbar. Added a new instance of the colorbar with this designated with the cax= (child axes) 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()

Upvotes: 4

Related Questions