Setting range of colorbar in the matplotlib hist2d plot

Question:

I have a simple hist2d in which I’d like to range the density (colorbar) between 0 to 1.

Here is my code:

plt.hist2d(x_values, y_values, bins=50, normed=True)
plt.colorbar(norm=colors.NoNorm)

How can it set the colorbar values between 0.0 to 1.0? e.g.: [0.0, 0.2, 0.4, 06, 0.8, 1.0]

enter image description here

Asked By: Kadu

||

Answers:

Add vmin=0, vmax=1 to the call to plt.hist2d:

import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
np.random.seed(2016)

N = 10**3
x_values = (np.random.random(size=N))*15
y_values = np.random.random(size=N)
plt.hist2d(x_values, y_values, bins=50, normed=True, vmin=0, vmax=1)
plt.colorbar(norm=mcolors.NoNorm)
plt.show()

The colorbar always associates itself to a single colorable artist. When no artist is supplied (as the mappable), the current colorable artist is used. In this case, it is the artist created by plt.hist2d. The vmin and vmax values of that artist affect the range of values displayed by the colorbar.

enter image description here

Answered By: unutbu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.