python - How to add colorbar to a histogram? -
i have histogram (just normal histogram):
in situation, there 20 bars (spanning x axis 0 1) , color of bar defined based on value on x axis.
what want add color spectrum 1 of in http://wiki.scipy.org/cookbook/matplotlib/show_colormaps @ bottom of histogram don't know how add it.
any appreciated!
you need specify color of faces form of colormap, example if want 20 bins , spectral
colormap,
nbins = 20 colors = plt.cm.spectral(np.linspace(nbins))
you can use specify color of bars, easiest getting histogram data first (using numpy
) , plotting bar chart. can add colorbar seperate axis @ bottom.
as minimal example,
import numpy np import matplotlib.pyplot plt import matplotlib mpl nbins = 20 minbin = 0. maxbin = 1. data = np.random.normal(size=10000) bins = np.linspace(minbin,maxbin,20) cmap = plt.cm.spectral norm = mpl.colors.normalize(vmin=data.min(), vmax=data.max()) colors = cmap(bins) hist, bin_edges = np.histogram(data, bins) fig = plt.figure() ax = fig.add_axes([0.05, 0.2, 0.9, 0.7]) ax1 = fig.add_axes([0.05, 0.05, 0.9, 0.1]) cb1 = mpl.colorbar.colorbarbase(ax1, cmap=cmap, norm=norm, orientation='horizontal') ax.bar(bin_edges[:-1], hist, width=0.051, color=colors, alpha=0.8) ax.set_xlim((0., 1.)) plt.show()
which yields,
Comments
Post a Comment