问题
I am trying to plot some 2D empirical probability distributions using matplotlib's histogram2d. I want the colours to be on the same scale across several different plots, but cannot find a way to set a scale even if I know a global upper and lower bound on the resulting distribution. As is, each color scale will run from the minimum height to the maximum height of the histogram bins, but this range will be different for each plot.
One potential solution would be to force one bin to take the height of my lower bound, and another my upper bound. Even this does not seem like a very straight forward task.
回答1:
In general, the color scaling of most things in matplotlib is controlled by the vmin
and vmax
keyword arguments.
You have to read between the lines a bit, but as the documentation mentions, additional kwargs in hist2d
are passed on to pcolorfast
. Therefore, you can specify the color limits through the vmin
and vmax
kwargs.
For example:
import numpy as np
import matplotlib.pyplot as plt
small_data = np.random.random((2, 10))
large_data = np.random.random((2, 100))
fig, axes = plt.subplots(ncols=2, figsize=(10, 5), sharex=True, sharey=True)
# For consistency's sake, we'll set the bins to be identical
bins = np.linspace(0, 1, 10)
axes[0].hist2d(*small_data, bins=bins, vmin=0, vmax=5)
axes[1].hist2d(*large_data, bins=bins, vmin=0, vmax=5)
plt.show()
来源:https://stackoverflow.com/questions/29236907/altering-height-range-of-matplotlib-histogram2d