Adding one colorbar to multiple plots in one graph

后端 未结 1 596
灰色年华
灰色年华 2021-01-27 09:18

I\'m trying to attach the colorbar to my MatplotLib plot which plots several plots in one graph (I\'m not looking for a single colorbar to multiple subplots).

相关标签:
1条回答
  • 2021-01-27 09:39

    This figure

    was produced running the following script

    from numpy import array, concatenate, linspace, cos, pi, sin
    import matplotlib.pyplot as plt
    
    from matplotlib.collections import LineCollection
    from matplotlib.colors import Normalize
    from matplotlib.cm import ScalarMappable
    
    def segments_from(x, y):
        tmp = array((x, y)).T.reshape(-1,1,2)
        return concatenate([tmp[:-1], tmp[1:]], axis=1)
    
    t = linspace(0, 3, 301)
    w1, w2 = 2*pi, 3*pi
    s1, s2 = sin(w1*t), sin(w2*t)
    c1, c2 = cos(w1*t), cos(w2*t)
    
    norm = Normalize(-2, +2)
    cmap = plt.get_cmap('inferno')
    
    fig, ax = plt.subplots()
    ax.set_xlim(0, 3)
    ax.set_ylim(-2, 2)
    
    for y, v in ((1.6*c1, c2), (0.9*s1, s2)):
        lc = LineCollection(segments_from(t, y),
                            linewidths=4,
                            norm=norm, cmap=cmap)
        lc.set_array(v)
        ax.add_collection(lc)
    
    fig.colorbar(ScalarMappable(norm=norm, cmap=cmap))
    
    plt.show()
    
    0 讨论(0)
提交回复
热议问题