How to draw vertical lines on a given plot in matplotlib

后端 未结 6 665
我寻月下人不归
我寻月下人不归 2020-11-28 18:27

Given a plot of signal in time representation, how to draw lines marking corresponding time index?

Specifically, given a signal plot with time index ranging from 0 t

6条回答
  •  孤独总比滥情好
    2020-11-28 19:14

    matplotlib.pyplot.vlines vs. matplotlib.pyplot.axvline

    • The difference is that vlines accepts 1 or more locations for x, while axvline permits one location.
      • Single location: x=37
      • Multiple locations: x=[37, 38, 39]
    • vlines takes ymin and ymax as a position on the y-axis, while axvline takes ymin and ymax as a percentage of the y-axis range.
      • When passing multiple lines to vlines, pass a list to ymin and ymax.
    • If you're plotting a figure with something like fig, ax = plt.subplots(), then replace plt.vlines or plt.axvline with ax.vlines or ax.axvline, respectively.
    import numpy as np
    import matplotlib.pyplot as plt
    
    xs = np.linspace(1, 21, 200)
    
    plt.figure(figsize=(10, 7))
    
    # only one line may be specified; full height
    plt.axvline(x=36, color='b', label='axvline - full height')
    
    # only one line may be specified; ymin & ymax spedified as a percentage of y-range
    plt.axvline(x=36.25, ymin=0.05, ymax=0.95, color='b', label='axvline - % of full height')
    
    # multiple lines all full height
    plt.vlines(x=[37, 37.25, 37.5], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple - full height')
    
    # multiple lines with varying ymin and ymax
    plt.vlines(x=[38, 38.25, 38.5], ymin=[0, 25, 75], ymax=[200, 175, 150], colors='teal', ls='--', lw=2, label='vline_multiple - partial height')
    
    # single vline with full ymin and ymax
    plt.vlines(x=39, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single - full height')
    
    # single vline with specific ymin and ymax
    plt.vlines(x=39.25, ymin=25, ymax=150, colors='green', ls=':', lw=2, label='vline_single - partial height')
    
    # place legend outside
    plt.legend(bbox_to_anchor=(1.0, 1), loc='upper left')
    
    plt.show()
    

提交回复
热议问题