嘿伙计们,我正在使用 matplotlib 绘制 3D 条形图。我想知道是否可以根据每个条形(总共 9 个)的值(dz)为每个条形赋予不同的颜色,并在此图中显示相应的级别。
非常感谢!
我的代码如下:
fig_stat=plt.figure(dpi=100)
ax_stat = fig_stat.add_subplot(111, projection='3d')
xpos = [1, 1, 1, 3, 3, 3, 5, 5, 5]
ypos = [1, 3, 5, 1, 3, 5, 1, 3, 5]
# initial z position (x-y plane), np.zeros(x), x
zpos = [0, 0, 0, 0, 0, 0, 0, 0, 0]
# x is the number of points you need
dx = np.ones(9)
dy = np.ones(9)
# dz = [1, 2, 3, 4, 10, 6, 7, 8, 9] # signal intensity
dz = col_stat.iloc[:, -2]
ax_stat.set_xlabel('X axis')
ax_stat.set_ylabel('Y axis')
ax_stat.set_zlabel('Signal Intensity')
ax_stat.bar3d(xpos, ypos, zpos, dx, dy, dz, color='#00ceaa')
plt.title("Position_{}".format(L))
最佳答案
bar3d
方法允许输入与数据数组长度相同的数组作为颜色。因此,可以使用颜色图来获取每个dz
对应的颜色:
from matplotlib import cm
from matplotlib.colors import Normalize
cmap = cm.get_cmap('plasma')
norm = Normalize(vmin=min(dz), vmax=max(dz))
colors = cmap(norm(dz))
并使用此颜色
作为bar3d颜色参数的输入,而不是'#00ceaa'
。之后,可以使用这段代码显示颜色条:
sc = cm.ScalarMappable(cmap=cmap,norm=norm)
sc.set_array([])
plt.colorbar(sc)
这将生成如下所示的图:
关于python - 如何使用matplotlib根据条形高度绘制具有特定颜色的3D条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50203580/