Yilun Zhang
Yilun Zhang

Reputation: 9018

How to add colorbar to a histogram?

I have a histogram like this (just like a normal histogram): enter image description here

In my situation, there are 20 bars always (spanning x axis from 0 to 1) and the color of the bar is defined based on the value on the x axis.

What I want is to add a color spectrum like one of those in http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps at the bottom of the histogram but I don't know how to add it.

Any help would be appreciated!

Upvotes: 4

Views: 8968

Answers (1)

Ed Smith
Ed Smith

Reputation: 13206

You need to specify the color of the faces from some form of colormap, for example if you want 20 bins and a spectral colormap,

nbins = 20
colors = plt.cm.spectral(np.linspace(nbins))

You can then use this to specify the color of the bars, which is probably easiest to do by getting histogram data first (using numpy) and plotting a bar chart. You can then add the colorbar to a seperate axis at the bottom.

As a minimal example,

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

nbins = 20
minbin = 0.
maxbin = 1.

data = np.random.normal(size=10000)
bins = np.linspace(minbin, maxbin, nbins)

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, enter image description here

Upvotes: 7

Related Questions