Plotting a line over several graphs

前端 未结 4 1462
孤城傲影
孤城傲影 2020-12-01 12:42

I don\'t know how this thing is called, or even how to describe it, so the title may be a little bit misleading.

The first attached graph was created with pyplot.

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

    Relevant documentation:
    http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.axvline

    Edit: since @DSM's answer was so much better than mine I have shamefully incorporated some of that answer in an attempt to make my answer less poor.

    I've tried to handle the somewhat-general case of multiple subplots in a column (i.e. not the even-more-general case of multiple subplots, e.g. in a grid).

    Thanks, @DSM, for your answer and @Artium for the question.

    import matplotlib.pyplot as plt
    import numpy as np
    
    def main():
        fig = plt.figure() 
    
        x = np.arange(20)
        y1 = np.cos(x)
        y2 = (x**2)
        y3 = (x**3)
        yn = (y1,y2,y3)
        cut = (x > 0) & (x % 2 == 0)
        COLORS = ('b','g','k')
    
        for i,y in enumerate(yn):
            ax = fig.add_subplot(len(yn),1,i+1)
    
            ax.plot(x, y,ls='solid', color=COLORS[i], zorder=1) 
            ax.scatter(x[cut], y[cut], c='r', zorder=2)
    
            if i != len(yn) - 1:
                ax.set_xticklabels( () )
    
            for j in x[cut]:
                if i != len(yn) - 1:
                    ax.axvline(x=j, ymin=-1.2, ymax=1,
                               c='r', lw=2, zorder=0, clip_on=False)
                else:
                    ax.axvline(x=j, ymin=0, ymax=1,
                               c='r', lw=2, zorder=0, clip_on=False)
    
        fig.suptitle('Matplotlib Vertical Line Example')
        plt.show()
    
    if __name__ == '__main__':
        main()
    

    enter image description here

提交回复
热议问题