有谁知道如何在 matplotlib 中轻松实现 3d 条形图的颜色图?
考虑这个例子,我如何根据颜色图更改每个条形?例如,短条应该以蓝色为主,而较高的条则将颜色从蓝色渐变为红色......
在物理科学中,想要一个所谓的乐高情节是很常见的,我认为这是原始用户想要的。凯文 G 的回答很好,让我得到了最终结果。这是一个更高级的直方图,用于 xy 散点数据,按高度着色:
xAmplitudes = np.random.exponential(10,10000) #your data here
yAmplitudes = np.random.normal(50,10,10000) #your other data here - must be same array length
x = np.array(xAmplitudes) #turn x,y data into numpy arrays
y = np.array(yAmplitudes) #useful for regular matplotlib arrays
fig = plt.figure() #create a canvas, tell matplotlib it's 3d
ax = fig.add_subplot(111, projection='3d')
#make histogram stuff - set bins - I choose 20x20 because I have a lot of data
hist, xedges, yedges = np.histogram2d(x, y, bins=(20,20))
xpos, ypos = np.meshgrid(xedges[:-1]+xedges[1:], yedges[:-1]+yedges[1:])
xpos = xpos.flatten()/2.
ypos = ypos.flatten()/2.
zpos = np.zeros_like (xpos)
dx = xedges [1] - xedges [0]
dy = yedges [1] - yedges [0]
dz = hist.flatten()
cmap = cm.get_cmap('jet') # Get desired colormap - you can change this!
max_height = np.max(dz) # get range of colorbars so we can normalize
min_height = np.min(dz)
# scale each z to [0,1], and get their rgb values
rgba = [cmap((k-min_height)/max_height) for k in dz]
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color=rgba, zsort='average')
plt.title("X vs. Y Amplitudes for ____ Data")
plt.xlabel("My X data source")
plt.ylabel("My Y data source")
plt.savefig("Your_title_goes_here")
plt.show()
Run Code Online (Sandbox Code Playgroud)
注意:结果将根据您选择的 bin 数量和使用的数据量而有所不同。此代码需要您插入一些数据或生成随机线性数组。结果图如下,有两个不同的观点: