pandas .plot() x-axis tick frequency — how can I show more ticks?

后端 未结 4 1827
梦毁少年i
梦毁少年i 2020-12-09 04:44

I am plotting time series using pandas .plot() and want to see every month shown as an x-tick.

Here is the dataset structure

Here is the result of the .plo

4条回答
  •  有刺的猬
    2020-12-09 05:28

    You could also format the x-axis ticks and labels of a pandas DateTimeIndex "manually" using the attributes of a pandas Timestamp object.

    I found that much easier than using locators from matplotlib.dates which work on other datetime formats than pandas (if I am not mistaken) and thus sometimes show an odd behaviour if dates are not converted accordingly.

    Here's a generic example that shows the first day of each month as a label based on attributes of pandas Timestamp objects:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    
    # data
    dim = 8760
    idx = pd.date_range('1/1/2000 00:00:00', freq='h', periods=dim)
    df = pd.DataFrame(np.random.randn(dim, 2), index=idx)
    
    # select tick positions based on timestamp attribute logic. see:
    # https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Timestamp.html
    positions = [p for p in df.index
                 if p.hour == 0
                 and p.is_month_start
                 and p.month in range(1, 13, 1)]
    # for date formatting, see:
    # https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
    labels = [l.strftime('%m-%d') for l in positions]
    
    # plot with adjusted labels
    ax = df.plot(kind='line', grid=True)
    ax.set_xlabel('Time (h)')
    ax.set_ylabel('Foo (Bar)')
    ax.set_xticks(positions)
    ax.set_xticklabels(labels)
    
    plt.show()
    

    yields:

    Hope this helps!

提交回复
热议问题