Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

Here is the dataset structure data set

Here is the result of the .plot()

enter image description here

I was trying to use examples from other posts and matplotlib documentation and do something like

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

But that removed all the ticks :(

I also tried to pass xticks = df.index, but it has not changed anything.

What would be the rigth way to show more ticks on x-axis?

like image 624
Rotkiv Avatar asked Sep 27 '16 01:09

Rotkiv


People also ask

How do I increase ticks in MatPlotLib?

Setting Figure-Level Tick Frequency in Matplotlib You can use the xticks() and yticks() functions and pass in an array denoting the actual ticks. On the X-axis, this array starts on 0 and ends at the length of the x array. On the Y-axis, it starts at 0 and ends at the max value of y .

How do I change the number of ticks in a plot in Python?

Locator_params() function that lets us change the tightness and number of ticks in the plots. This is made for customizing the subplots in matplotlib, where we need the ticks packed a little tighter and limited. So, we can use this function to control the number of ticks on the plots.

How do you show all X ticks in Python?

To show all X coordinates (or Y coordinates), we can use xticks() method (or yticks()).


1 Answers

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() 
  • formatted x-axis with set_major_locator

enter image description here

  • unformatted x-axis

enter image description here

like image 133
Kyle Avatar answered Sep 22 '22 21:09

Kyle