Matplotlib 3D瀑布情节与彩色高度

Ian*_*rts 7 python 3d matplotlib surface matplotlib.mlab

我正在尝试使用Python和Matplotlib可视化3D中的数据集,该数据集包含xz数据的时间序列(沿y).

我想创建一个如下图所示的图(用Python制作:http://austringer.net/wp/index.php/2011/05/20/plotting-a-dolphin-biosonar-click-train /),但颜色随Z变化 - 即,为了清楚起见,强度由色图和峰高显示.

在此输入图像描述

显示Z中的色彩映射的示例(显然是使用MATLAB制作的): 在此输入图像描述

可以使用MATLAB中的瀑布绘图选项创建此效果,但我知道在Python中没有直接的等效.

我也尝试在Python(下面)中使用plot_surface选项,它工作正常,但我想"强制"在表面上运行的线只在x方向(即使它看起来更像堆叠时间系列比表面).这可能吗? 在此输入图像描述

任何帮助或建议都非常欢迎.谢谢.

Ori*_*ril 5

我已经生成了一个在 matplotlib 中复制 matlab 瀑布行为的函数,但我认为在性能方面它不是最佳解决方案。

我从 matplotlib 文档中的两个示例开始:多色线3d 图中的多条线。从这些示例中,我只看到可以根据示例中的 z 值绘制颜色随给定颜色图变化的线,该示例正在重塑输入数组以按 2 点的线段绘制线并将线段的颜色设置为2 点之间的 z 平均值。

因此,给定输入矩阵n,m矩阵XYZ,该函数在 之间的最小维度上循环,n,m以像示例中那样通过 2 点段绘制每条线,其中按段绘制的重塑是使用与以下代码相同的代码重塑数组来完成的:例子。

def waterfall_plot(fig,ax,X,Y,Z):
    '''
    Make a waterfall plot
    Input:
        fig,ax : matplotlib figure and axes to populate
        Z : n,m numpy array. Must be a 2d array even if only one line should be plotted
        X,Y : n,m array
    '''
    # Set normalization to the same values for all plots
    norm = plt.Normalize(Z.min().min(), Z.max().max())
    # Check sizes to loop always over the smallest dimension
    n,m = Z.shape
    if n>m:
        X=X.T; Y=Y.T; Z=Z.T
        m,n = n,m

    for j in range(n):
        # reshape the X,Z into pairs 
        points = np.array([X[j,:], Z[j,:]]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)        
        lc = LineCollection(segments, cmap='plasma', norm=norm)
        # Set the values used for colormapping
        lc.set_array((Z[j,1:]+Z[j,:-1])/2)
        lc.set_linewidth(2) # set linewidth a little larger to see properly the colormap variation
        line = ax.add_collection3d(lc,zs=(Y[j,1:]+Y[j,:-1])/2, zdir='y') # add line to axes

    fig.colorbar(lc) # add colorbar, as the normalization is the same for all, it doesent matter which of the lc objects we use
Run Code Online (Sandbox Code Playgroud)

因此,可以使用与 matplotlib 曲面图相同的输入矩阵轻松生成看起来像 matlab 瀑布图的图:

import numpy as np; import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from mpl_toolkits.mplot3d import Axes3D

# Generate data
x = np.linspace(-2,2, 500)
y = np.linspace(-2,2, 40)
X,Y = np.meshgrid(x,y)
Z = np.sin(X**2+Y**2)
# Generate waterfall plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
waterfall_plot(fig,ax,X,Y,Z) 
ax.set_xlabel('X') ; ax.set_xlim3d(-2,2)
ax.set_ylabel('Y') ; ax.set_ylim3d(-2,2)
ax.set_zlabel('Z') ; ax.set_zlim3d(-1,1)
Run Code Online (Sandbox Code Playgroud)

瀑布图

该函数假设生成网格时,x数组是最长的,并且默认情况下,线的 y 坐标是固定的,而 x 坐标是变化的。但是,如果 y 维度的大小较大,则矩阵会转置,生成具有固定 x 的线。len(x)=40因此,生成尺寸反转 (和)的网格会产生len(y)=500

非默认瀑布图