Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting matplotlib colorbar range (larger range than the values plotted)

I want to plot some data (between 0 and 18) but I want the colorbar to show a range between 0 and 40. After going through several online examples, I have no idea on how to achieve what I need!

Here is a simple example:

import matplotlib.pyplot as plt
import numpy as np

rd = np.random.rand(40,100) # random samples from a uniform distribution over [0, 1]
surface = 18 * rd           # maximum value will be 18

fig = plt.figure()
ax = fig.add_subplot(111)
cores = ax.contourf(surface[:], vmin=0, vmax=40)

cbar = plt.colorbar(cores)

I've tried this as well:

cbar = plt.colorbar(cores, extend='both', extendrect=True)
cbar.set_clim(0, 40.)

But I keep getting the same image, with a colorbar ranging from 0 to 20! I know I could use the set_over method, but I don't want to get a single color... I want my whole color range (as defined in cores, from 0 to 40) to appear!

enter image description here

Thanks for your help!

like image 595
carla Avatar asked Mar 10 '17 16:03

carla


1 Answers

I finally managed to solve it. Instead of vmin and vmax, I must pass a keyword to control the levels to draw, like this:

import matplotlib.pyplot as plt
import numpy as np

rd = np.random.rand(40,100)
surface = 18 * rd           # maximum value will be 18

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

cores = ax.contourf(surface[:], levels=range(41))
cbar = plt.colorbar(cores)

plt.show()

And I get the image I wanted: enter image description here

like image 126
carla Avatar answered Sep 21 '22 23:09

carla