【发布时间】:2017-04-12 17:19:03
【问题描述】:
我在python中有一个包含3维数据的元组列表,其中每个元组的形式为:(x,y,z,data_value),即,我在每个(x,y,z)处都有数据值协调。我想制作一个 3D 离散热图,其中颜色代表我的元组列表中 data_values 的值。在这里,我给出了一个二维数据集的热图示例,其中我有一个 (x, y, data_value) 元组列表:
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
from random import randint
# x and y coordinates
x = np.array(range(10))
y = np.array(range(10,15))
data = np.zeros((len(y),len(x)))
# Generate some discrete data (1, 2 or 3) for each (x, y) pair
for i,yy in enumerate(y):
for j, xx in enumerate(x):
data[i,j] = randint(1,3)
# Map 1, 2 and 3 to 'Red', 'Green' qnd 'Blue', respectively
colormap = colors.ListedColormap(['Red', 'Green', 'Blue'])
colorbar_ticklabels = ['1', '2', '3']
# Use matshow to create a heatmap
fig, ax = plt.subplots()
ms = ax.matshow(data, cmap = colormap, vmin=data.min() - 0.5, vmax=data.max() + 0.5, origin = 'lower')
# x and y axis ticks
ax.set_xticklabels([str(xx) for xx in x])
ax.set_yticklabels([str(yy) for yy in y])
ax.xaxis.tick_bottom()
# Put the x- qnd y-axis ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]), minor = False)
ax.set_yticks(np.arange(data.shape[0]), minor = False)
# Set custom ticks and ticklabels for color bar
cbar = fig.colorbar(ms,ticks = np.arange(np.min(data),np.max(data)+1))
cbar.ax.set_yticklabels(colorbar_ticklabels)
plt.show()
如果我的数据具有第三维,我如何在 3D 空间中制作类似的图(即具有 z 轴)。例如,如果
# x and y and z coordinates
x = np.array(range(10))
y = np.array(range(10,15))
z = np.array(range(15,20))
data = np.zeros((len(y),len(x), len(y)))
# Generate some random discrete data (1, 2 or 3) for each (x, y, z) triplet.
# Am I defining i, j and k correctly here?
for i,yy in enumerate(y):
for j, xx in enumerate(x):
for k, zz in enumerate(z):
data[i,j, k] = randint(1,3)
我听起来plot_surface in mplot3d应该可以做到这一点,但是这个函数的输入中的z本质上是数据在(x, y)坐标处的值,即(x, y, z = data_value),这与我所拥有的不同,即(x,y,z,data_value)。
【问题讨论】:
-
您想要一个 3d 表面,其中绘图的颜色是 x、y 和 z 的函数?
-
正确!不过有一个离散的颜色条。
-
您可能想查看
mayavi的contour3d,它允许您在 3d 中绘制标量场的等值面。 -
如果您不介意语言转换和许可问题,Mathematica 内置了
Image3D、ContourPlot3D -
Mathematica 中的 Image3D 听起来很像我想要的。我只是希望在 python/matplotlib 中有一个等价物。
标签: python matplotlib heatmap