Having line color vary with data index for line graph in matplotlib?

前端 未结 4 1714
挽巷
挽巷 2020-12-06 06:56

So I have a 2D array of data producing a plot of many timeseries on the same axes. At the moment, the colour of each line just cycles through and doesn\'t mean anything.

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-06 07:36

    if someone is still looking for a way to color the curve along the path using some colormap, without using a scatter, I think the better way is to split it to segments and call colormap for the color

    import matplotlib.pyplot as plt
    import numpy as np
    
    def plot_colored(x, y, c, cmap=plt.cm.jet, steps=10):
        c = np.asarray(c)
        c -= c.min()
        c /= c.max()
        it=0
        while it<с.size-steps:
            x_segm = x[it:it+steps+1]
            y_segm = y[it:it+steps+1]
            c_segm = cmap( c[it+steps//2] )
            plt.plot(x_segm, y_segm, c=c_segm)
            it += steps
    
    # sample track
    t = np.r_[0:10:1000j]
    x = t**.25*np.sin(2*np.pi*t)
    y = t**.25*np.cos(2*np.pi*t)
    
    plt.figure()
    plot_colored(x, y, t)
    

    (smaller step makes it smoother but slower) example

提交回复
热议问题