Matplotlib Plot Lines with Colors Through Colormap

前端 未结 4 2144
眼角桃花
眼角桃花 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:19

    An anternative to Bart's answer, in which you do not specify the color in each call to plt.plot is to define a new color cycle with set_prop_cycle. His example can be translated into the following code (I've also changed the import of matplotlib to the recommended style):

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.linspace(0, 2*np.pi, 64)
    y = np.cos(x) 
    
    n = 20
    ax = plt.axes()
    ax.set_prop_cycle('color',[plt.cm.jet(i) for i in np.linspace(0, 1, n)])
    
    for i in range(n):
        plt.plot(x, i*y)
    

提交回复
热议问题