python - 如何使用matplotlib根据条形高度绘制具有特定颜色的3D条形图

标签 python python-3.x matplotlib 3d

enter image description here

嘿伙计们,我正在使用 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)

这将生成如下所示的图:

bar cmap

关于python - 如何使用matplotlib根据条形高度绘制具有特定颜色的3D条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50203580/

相关文章:

python - 组合函数和功能模块

python - 无法从网页中抓取标题

python - 使用多索引重新索引并创建空日期

python - Matplotlib 导航工具栏嵌入 pyqt5 窗口 - 重置原始 View 崩溃

python - Pyparsing 是否支持上下文相关语法?

python - Facebook 连接 : redirect to white page with only the facebook logo on it (amazon ec2)

python - 用于维基解密电缆的基于 python 的容错解析器

python - celery 通过在 task_postrun 信号中提高 SystemExit 来尝试关闭 worker 但总是挂起并且主进程永远不会退出

python - 绘制非结构化三角形曲面 Python

python - 使用 matplotlib 注释绘图