Matplotlib: Add colorbar to non-mappable object

前端 未结 1 1072
野的像风
野的像风 2020-12-01 10:54

I have a series of lines representing the change of a variable; each with a unique color. For that reason I want to add a colorbar next to the plot. The desired output is sh

相关标签:
1条回答
  • 2020-12-01 11:40

    You may define your own ScalarMappable and use it just as if it was present in the plot.
    (Note that I changed the numbero f colors to 21 to have nice spacings of 0.1)

    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    
    x = np.linspace(0, 5, 100)
    N = 21
    cmap = plt.get_cmap('jet',N)
    
    fig = plt.figure(figsize=(8,6))
    ax1 = fig.add_axes([0.10,0.10,0.70,0.85])
    
    for i,n in enumerate(np.linspace(0,2,N)):
        y = np.sin(x)*x**n
        ax1.plot(x,y,c=cmap(i))
    
    plt.xlabel('x')
    plt.ylabel('y')
    
    norm = mpl.colors.Normalize(vmin=0,vmax=2)
    sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
    sm.set_array([])
    plt.colorbar(sm, ticks=np.linspace(0,2,N), 
                 boundaries=np.arange(-0.05,2.1,.1))
    
    
    plt.show()
    

    0 讨论(0)
提交回复
热议问题