How do you plot a vertical line on a time series plot in Pandas?

后端 未结 4 1475
花落未央
花落未央 2020-11-28 22:56
  • How do you plot a vertical line (vlines) in a Pandas series plot?
  • I am using Pandas to plot rolling means, etc., and would like to mark important
4条回答
  •  孤城傲影
    2020-11-28 23:26

    matplotlib.pyplot.vlines

    • For a time series, the dates for the axis must be proper datetime objects, not strings.
      • Use pandas.to_datetime to convert columns to datetime dtype.
    • Allows for single or multiple locations
    • ymin & ymax are specified as a specific y-value, not as a percent of ylim
    • If referencing axes with something like fig, axes = plt.subplots(), then change plt.xlines to axes.xlines

    plt.plot() & sns.lineplot()

    from datetime import datetime
    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    import seaborn as sns  # if using seaborn
    
    plt.style.use('seaborn')  # these plots use this style
    
    # configure synthetic dataframe
    df = pd.DataFrame(index=pd.bdate_range(datetime(2020, 6, 8), freq='1d', periods=500).tolist())
    df['v'] = np.logspace(0, 1, num=len(df))
    
    # plot
    plt.plot('v', data=df, color='magenta')
    
    y_min = df.v.min()
    y_max = df.v.max()
    
    plt.vlines(x=['2020-07-14', '2021-07-14'], ymin=y_min, ymax=y_max, colors='purple', ls='--', lw=2, label='vline_multiple')
    plt.vlines(x=datetime(2021, 9, 14), ymin=4, ymax=9, colors='green', ls=':', lw=2, label='vline_single')
    plt.legend(bbox_to_anchor=(1.04, 0.5), loc="center left")
    plt.show()
    

    df.plot()

    df.plot(color='magenta')
    
    ticks, _ = plt.xticks()
    print(f'Date format is pandas api format: {ticks}')
    
    y_min = df.v.min()
    y_max = df.v.max()
    
    plt.vlines(x=['2020-07-14', '2021-07-14'], ymin=y_min, ymax=y_max, colors='purple', ls='--', lw=2, label='vline_multiple')
    plt.vlines(x='2020-12-25', ymin=y_min, ymax=8, colors='green', ls=':', lw=2, label='vline_single')
    plt.legend(bbox_to_anchor=(1.04, 0.5), loc="center left")
    plt.show()
    

    package versions

    import matplotlib as mpl
    
    print(mpl.__version__)
    print(sns.__version__)
    print(pd.__version__)
    
    [out]:
    3.3.1
    0.10.1
    1.1.0
    
    

提交回复
热议问题