Creating a 2d colour gradient plot with 3 1D arrays
Question: So i have 3 1D arrays, x_vals, y_vals and z_vals.

I would like to plot x_vals against y_vals, with z_vals defining the colour at
the point.

from everything i have looked up it seems i need to use numpy.meshgrid,
however when i try this python just times out.

Any thoughts? Thank you!


Answer: You are looking for the `LineCollection` command. Try this

    
    
    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.collections import LineCollection
    
    fig,ax = plt.subplots(1)
    
    # some data to plot
    x = np.linspace(0,1,200)
    y = np.sin(10*x)
    z = x**2
    
    # creating the segments
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    
    # creating LineCollection object
    lc = LineCollection(segments, cmap=plt.get_cmap('jet'),norm=plt.Normalize(0, 1))
    lc.set_array(z)
    lc.set_linewidth(2)
    
    # add LineCollection to plot
    ax.add_collection(lc)
    
    # set plotting range
    ax.set_xlim((0,1))
    ax.set_ylim((-1,1))
    
    plt.show()
    

