[Python] Colormap a 3D curve in matplotlib

Discussão em 'Python' iniciado por Stack, Junho 3, 2025.

  1. Stack

    Stack Membro Participativo

    I have 4 arrays x, y, z and T of length n and I want to plot a 3D curve using matplotlib. The (x, y, z) are the points positions and T is the value of each point (which is plotted as color), like the temperature of each point. How can I do it?

    Example code:

    import numpy as np
    from matplotlib import pyplot as plt

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    n = 100
    cmap = plt.get_cmap("bwr")
    theta = np.linspace(-4 * np.pi, 4 * np.pi, n)
    z = np.linspace(-2, 2, n)
    r = z**2 + 1
    x = r * np.sin(theta)
    y = r * np.cos(theta)
    T = (2*np.random.rand(n) - 1) # All the values are in [-1, 1]


    What I found over the internet:


    ax = plt.gca()
    ax.scatter(x, y, z, cmap=cmap, c=T)


    The problem is that scatter is a set of points, not a curve.


    t = (T - np.min(T))/(np.max(T)-np.min(T)) # Normalize
    for i in range(n-1):
    plt.plot(x[i:i+2], y[i:i+2], z[i:i+2], c=cmap(t)


    The problem is that each segment has only one color, but it should be an gradient. The last value is not even used.

    Useful links:


    Continue reading...

Compartilhe esta Página