如何将颜色条添加到直方图? [英] How to add colorbar to a histogram?
问题描述
我有一个像这样的直方图(就像普通的直方图一样):
I have a histogram like this (just like a normal histogram):
在我的情况下,总是有20条(x轴从0到1跨度),并且条的颜色是根据x轴上的值定义的.
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.
我要添加的光谱类似于 http://wiki中的光谱之一.scipy.org/Cookbook/Matplotlib/Show_colormaps 位于直方图的底部,但我不知道如何添加.
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.
任何帮助将不胜感激!
推荐答案
您需要从某种形式的颜色表中指定面部的颜色,例如,如果要20个bin和一个spectral
颜色表,
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))
然后可以使用它来指定条形的颜色,这可能最容易通过首先获取直方图数据(使用numpy
)并绘制条形图来完成.然后,您可以将颜色栏添加到底部的单独轴上.
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.
作为一个最小的例子,
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()
哪个产量,
这篇关于如何将颜色条添加到直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!