Drawing a colorbar aside a line plot, using Matplotlib

前端 未结 1 2004
难免孤独
难免孤独 2020-12-17 03:55

I\'m trying to add a color bar in a graph, but I don\'t understand how it works. The problem is that I make my own colorcode by:

x = np.arange(11)

ys = [i+x         


        
相关标签:
1条回答
  • 2020-12-17 04:16

    Drawing a colorbar aside a line plot

    Please map my solution (I used simply 11 sines of different amplitudes) to your problem (as I told you, it is difficult to understand from what you wrote in your Q).

    import matplotlib
    import numpy as np
    from matplotlib import pyplot as plt
    
    # an array of parameters, each of our curves depend on a specific
    # value of parameters
    parameters = np.linspace(0,10,11)
    
    # norm is a class which, when called, can normalize data into the
    # [0.0, 1.0] interval.
    norm = matplotlib.colors.Normalize(
        vmin=np.min(parameters),
        vmax=np.max(parameters))
    
    # choose a colormap
    c_m = matplotlib.cm.cool
    
    # create a ScalarMappable and initialize a data structure
    s_m = matplotlib.cm.ScalarMappable(cmap=c_m, norm=norm)
    s_m.set_array([])
    
    # plotting 11 sines of varying amplitudes, the colors are chosen
    # calling the ScalarMappable that was initialised with c_m and norm
    x = np.linspace(0,np.pi,31)
    for parameter in parameters:
        plt.plot(x,
                 parameter*np.sin(x),
                 color=s_m.to_rgba(parameter))
    
    # having plotted the 11 curves we plot the colorbar, using again our
    # ScalarMappable
    plt.colorbar(s_m)
    
    # That's all, folks
    plt.show()
    

    Example

    Curves+colormap

    Acknowledgements

    A similar problem, about a scatter plot

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