3

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!

TYZ
  • 8,466
  • 5
  • 29
  • 60
  • You can add another subplot. The answers [in this SO post](http://stackoverflow.com/questions/13784201/matplotlib-2-subplots-1-colorbar) will help. – WGS Jun 03 '15 at 02:54
  • 3
    Please show the code you're using to generate the graph. It will help us tailor the answer to your use case. – leekaiinthesky Jun 03 '15 at 04:39

1 Answers1

7

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

Ed Smith
  • 12,716
  • 2
  • 43
  • 55
  • This is exactly what I wanted! Thanks. I will try to apply this to multi subplots. – TYZ Jun 03 '15 at 16:29
  • I get that I can iterate through a colormap to place different colors along varying x-values. If one wanted the colormap to coincide with the y-values, is there a simpler way then using inverse functions? –  Apr 26 '17 at 05:30