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

后端 未结 4 1828
梦毁少年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:06

    No need to pass any args to MonthLocator. Make sure to use x_compat in the df.plot() call per @Rotkiv's answer.

    import pandas as pd
    import numpy as np
    import matplotlib.pylab as plt
    import matplotlib.dates as mdates
    
    df = pd.DataFrame(np.random.rand(100,2), index=pd.date_range('1-1-2018', periods=100))
    ax = df.plot(x_compat=True)
    ax.xaxis.set_major_locator(mdates.MonthLocator())
    plt.show()
    
    0 讨论(0)
  • 2020-12-09 05:11

    If you want to just show more ticks, you can also dive deep into the structure of pd.plotting._converter:

    dai = ax.xaxis.minor.formatter.plot_obj.date_axis_info
    dai['fmt'][dai['fmt'] == b''] = b'%b'
    

    After plotting, the formatter is a TimeSeries_DateFormatter and _set_default_format has been called, so self.plot_obj.date_axis_info is not None. You can now manipulate the structured array .date_axis_info to be to your liking, namely contain less b'' and more b'%b'

    0 讨论(0)
  • 2020-12-09 05:14

    The right way to do that described here Using the x_compat parameter, it is possible to suppress automatic tick resolution adjustment

    df.A.plot(x_compat=True)

    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题