5

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!

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much! That was driving me absolutely crazy; I love how powerful matplotlib is, but the number of undocumented features and resulting unexpected behaviors can be absolutely infuriating.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.