gpt4 book ai didi

python - 对直方图进行颜色编码

转载 作者:太空宇宙 更新时间:2023-11-03 18:35:54 25 4
gpt4 key购买 nike

我有一组 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()

最佳答案

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

关于python - 对直方图进行颜色编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21610858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com