在3D中绘制切片作为热图

时间:2019-06-20 14:49:43

标签: python numpy matplotlib

如何在python上可视化4d数据,例如我有这样的数据:

merge()

我想像这样可视化数据:

visualize on matlab

ps:我尝试像这样在matlab上使用slice函数

dput(intervals)
structure(list(bike_id = c(28780L, 28780L, 28780L, 28780L, 28780L, 
28780L), start = structure(c(1556858685, 1556953659, 1557271712, 
1557468381, 1557638484, 1557737094), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), end = structure(c(1556902736, 1556981309, 
1557320184, 1557493928, 1557660952, 1557750511), class = c("POSIXct", 
"POSIXt"), tzone = "UTC"), id = c(1, 2, 3, 4, 5, 6)), row.names = c(NA, 
-6L), class = c("data.table", "data.frame"), .internal.selfref = <pointer: 0x1030056e0>)

dput(records)
structure(list(bike_id = c(28780L, 28780L, 28780L, 28780L, 28780L, 
28780L), created_at = structure(c(1556872158.796, 1556917528.845, 
1557004419.928, 1557249860.939, 1557315272.396, 1557358719.333
), class = c("POSIXct", "POSIXt"), tzone = "UTC"), resolved_at = structure(c(1556872537.867, 
1556917648.118, 1557004540.056, 1557249999.892, 1557317804.183, 
1557358836.202), class = c("POSIXct", "POSIXt"), tzone = "UTC")), row.names = c(NA, 
6L), class = "data.frame")

1 个答案:

答案 0 :(得分:1)

您可以按照以下功能使用plot_surface中建议的this answer

import numpy as np
import scipy.interpolate
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

# Plot slices of the data at the given coordinates
def plot_slices(x, y, z, data, xslice, yslice, zslice, ax=None):
    if ax is None:
        ax = plt.figure().add_subplot(111, projection='3d')
    # Normalize data to [0, 1] range
    vmin, vmax = data.min(), data.max()
    data_n = (data - vmin) / (vmax - vmin)
    # Take slices interpolating to allow for arbitrary values
    data_x = scipy.interpolate.interp1d(x, data, axis=0)(xslice)
    data_y = scipy.interpolate.interp1d(y, data, axis=1)(yslice)
    data_z = scipy.interpolate.interp1d(z, data, axis=2)(zslice)
    # Pick color map
    cmap = plt.cm.plasma
    # Plot X slice
    xs, ys, zs = data.shape
    xplot = ax.plot_surface(xslice, y[:, np.newaxis], z[np.newaxis, :],
                            rstride=1, cstride=1, facecolors=cmap(data_x), shade=False)
    # Plot Y slice
    yplot = ax.plot_surface(x[:, np.newaxis], yslice, z[np.newaxis, :],
                            rstride=1, cstride=1, facecolors=cmap(data_y), shade=False)
    # Plot Z slice
    zplot = ax.plot_surface(x[:, np.newaxis], y[np.newaxis, :], np.atleast_2d(zslice),
                            rstride=1, cstride=1, facecolors=cmap(data_z), shade=False)
    return xplot, yplot, zplot

然后您将像这样使用它:

import numpy as np

np.random.seed(0)
x = np.linspace(0, 10, 10)
y = np.linspace(20, 50, 30)
z = np.linspace(-10, 5, 15)
t = np.random.random((10, 30, 15))
ax = plt.figure().add_subplot(111, projection='3d')
plot_slices(x, y, z, t, 5, 35, 0, ax=ax)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

输出:

Data slices

不幸的是,Matplotlib无法很好地处理相交的3D对象,并且裁剪不正确,但这是另一种问题。