[Python] 3D scatter plot and projected KDE plots

Discussão em 'Python' iniciado por Stack, Março 7, 2025.

  1. Stack

    Stack Membro Participativo

    Can someone tell me why the xz projection in this code does not appear on the x-z plane?

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

    # Sample data
    np.random.seed(42)
    x = np.random.randn(100)
    y = np.random.randn(100)
    z = np.random.randn(100)

    # Create figure and 3D axes
    fig = plt.figure(figsize=(10, 8))
    ax = fig.add_subplot(111, projection='3d')

    # Scatter plot
    ax.scatter(x, y, z, c='b', marker='o')

    # KDE for projections
    def kde_projection(data1, data2):
    values = np.vstack([data1, data2])
    kernel = kde.gaussian_kde(values)

    x_range = np.linspace(data1.min(), data1.max(), 100)
    y_range = np.linspace(data2.min(), data2.max(), 100)
    X, Y = np.meshgrid(x_range, y_range)
    positions = np.vstack([X.ravel(), Y.ravel()])
    Z = np.reshape(kernel(positions).T, X.shape)
    return X, Y, Z

    # Projections with KDE
    # XY plane
    X_xy, Y_xy, Z_xy = kde_projection(x, y)
    ax.contour(X_xy, Y_xy, Z_xy, zdir='z', offset=z.min()-1, cmap='Blues')

    # XZ plane
    X_xz, Z_xz, Y_xz = kde_projection(x, z)
    ax.contour(X_xz, Y_xz, Z_xz, zdir='y', offset=y.min()-1, cmap='Reds')

    # YZ plane
    Y_yz, Z_yz, X_yz = kde_projection(y, z)
    ax.contour(X_yz, Y_yz, Z_yz, zdir='x', offset=x.min()-1, cmap='Greens')

    # Set labels and limits
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')

    ax.set_xlim(x.min() - 1, x.max() + 1)
    ax.set_ylim(y.min() - 1, y.max() + 1)
    ax.set_zlim(z.min() - 1, z.max() + 1)

    # Show plot
    plt.show()


    It correcly plots the yz and xy projections onto their respective planes, but xz doesn't want to work... I'm not sure if I'm missing something, but I think the pattern should hold for all three planes.

    Thanks.

    Continue reading...

Compartilhe esta Página