Kadu
Kadu

Reputation: 373

Setting range of colorbar in the matplotlib hist2d plot

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

Upvotes: 3

Views: 5754

Answers (1)

unutbu
unutbu

Reputation: 880489

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

Upvotes: 5

Related Questions