Matplotlib Plot Lines with Colors Through Colormap

前端 未结 4 2135
眼角桃花
眼角桃花 2020-12-01 03:11

I am plotting multiple lines on a single plot and I want them to run through the spectrum of a colormap, not just the same 6 or 7 colors. The code is akin to this:



        
4条回答
  •  爱一瞬间的悲伤
    2020-12-01 03:18

    The Matplotlib colormaps accept an argument (0..1, scalar or array) which you use to get colors from a colormap. For example:

    col = plt.cm.jet([0.25,0.75])    
    

    Gives you an array with (two) RGBA colors:

    array([[ 0. , 0.50392157, 1. , 1. ], [ 1. , 0.58169935, 0. , 1. ]])

    You can use that to create N different colors:

    import numpy as np
    import matplotlib.pylab as pl
    
    x = np.linspace(0, 2*np.pi, 64)
    y = np.cos(x) 
    
    pl.figure()
    pl.plot(x,y)
    
    n = 20
    colors = pl.cm.jet(np.linspace(0,1,n))
    
    for i in range(n):
        pl.plot(x, i*y, color=colors[i])
    

提交回复
热议问题