【问题标题】:Color-coding a histogram对直方图进行颜色编码
【发布时间】:2014-02-06 18:19:12
【问题描述】:

我有一组具有两个属性的 N 个对象:x 和 y。 我想使用 hist() 在 MATPLOTLIB 中用直方图描述 x 的分布。很容易。现在,我想用一种颜色对直方图的每个条形进行颜色编码,该颜色表示该集合中 y 的平均值,并带有一个颜色图。是否有捷径可寻?这里,x 和 y 都是 N-d numpy 数组。谢谢!

fig = plt.figure()
n, bins, patches = plt.hist(x, 100, normed=1, histtype='stepfilled')
plt.setp(patches, 'facecolor', 'g', 'alpha', 0.1)
plt.xlabel('x')
plt.ylabel('Normalized frequency')
plt.show()

【问题讨论】:

  • 您正在捕获返回的patches 对象,您不能根据bins 对其进行迭代并设置您认为合适的颜色吗?
  • 所以我必须手动检查 N 个对象中的每一个,它们在哪个 bin 中,记录那里的 y,最后取平均 y 来确定颜色?
  • 类似的东西;首先,我可能会将 x 和 y 组合成一个数组,然后按 x 对其进行排序。之后,遍历数据,对 y 求和,然后在看到 x 越过 bin 边界时进行平均和着色。
  • 这实际上是一个比matplotlib 问题更有趣的numpy 问题

标签: python numpy matplotlib


【解决方案1】:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# set up the bins
Nbins = 10
bins = np.linspace(0, 1, Nbins +1, endpoint=True)
# get some fake data
x = np.random.rand(300)
y = np.arange(300)
# figure out which bin each x goes into
bin_num = np.digitize(x, bins, right=True) - 1
# compute the counts per bin
hist_vals = np.bincount(bin_num)
# set up array for bins
means = np.zeros(Nbins)
# numpy slicing magic to sum the y values by bin
means[bin_num] += y
# take the average
means /= hist_vals

# make the figure/axes objects
fig, ax = plt.subplots(1,1)
# get a color map
my_cmap = cm.get_cmap('jet')
# get normalize function (takes data in range [vmin, vmax] -> [0, 1])
my_norm = Normalize()
# use bar plot 
ax.bar(bins[:-1], hist_vals, color=my_cmap(my_norm(means)), width=np.diff(bins))

# make sure the figure updates
plt.draw()
plt.show()

相关:vary the color of each bar in bargraph using particular value

【讨论】:

猜你喜欢
  • 2012-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-15
  • 2018-12-28
  • 2017-08-20
相关资源
最近更新 更多