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

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

Here is the data set structure data set

Here is the result of .plot ()

enter image description here

I tried using examples from other posts and matplotlib documentation and doing something like

ax.xaxis.set_major_locator( dates.MonthLocator(revenue_pivot.index, bymonthday=1,interval=1)) 

But this removed all the tics :(

I also tried passing xticks = df.index , but didn't change anything.

What would be the way to show more ticks along the x axis?

+8
matplotlib pandas
source share
3 answers

The correct way to do this is described here. Using the x_compat parameter, you can turn off automatic tick resolution adjustment

df.A.plot(x_compat=True)

+2
source share

No need to pass any arguments to MonthLocator . Be sure to use x_compat in the df.plot() response for the @Rotkiv 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() 
+2
source share

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

I found this to be much simpler than using locators from matplotlib.dates , which work with other datetime formats than pandas (if I'm not mistaken), and therefore sometimes show odd behavior if dates are not converted accordingly.

Here is a general example that shows the first day of each month as a label based on the 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() 

gives:

enter image description here

Hope this helps!

+1
source share

All Articles