Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the datetime tick label frequency for matplotlib plots?

Tags:

Below shows a plot of simulated data, which contains the xticks that I want to modify. By default, the pd.df.plot chooses dates that are approximately 3 months apart as ticks. But what I want is each month being a tick. What is the best way to do this? What about seasonal ticks? Thank you in advance.

enter image description here

like image 542
MLhacker Avatar asked Aug 16 '17 02:08

MLhacker


People also ask

How do I make ticks longer in MatPlotLib?

To make longer subplot tick marks in matplotlib, we can use tick_params() method for minor and major ticks length and width.

What is the use of Xticks () and Yticks () in plotting?

The xticks() and yticks() function takes a list object as argument. The elements in the list denote the positions on corresponding action where ticks will be displayed. This method will mark the data points at the given positions with ticks.


1 Answers

First of all you have to convert pandas date objects to python date objects. This conversion is needed because of matplotlib internal date conversion functions. Then use functions from matplotlib.dates to set desired formatter and tick positions like here:

import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import matplotlib.dates as mdates

# convert date objects from pandas format to python datetime
index = pd.date_range(start = "2015-07-01", end = "2017-01-01", freq = "D")
index = [pd.to_datetime(date, format='%Y-%m-%d').date() for date in index]
data = np.random.randint(1,100, size=len(index))
df = pd.DataFrame(data=data,index=index, columns=['data'])
print (df.head())

ax = df.plot()
# set monthly locator
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=1))
# set formatter
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))
# set font and rotation for date tick labels
plt.gcf().autofmt_xdate()

plt.show()

For season labels you have to construct it by yourself and then set it with plt.setp function (for month 02 set label winter, 04 - spring etc.): plt.setp(new_labels, rotation=90, fontsize=9).

enter image description here

head of df:

            data
2015-07-01    26
2015-07-02    33
2015-07-03    46
2015-07-04    69
2015-07-05    17
like image 130
Serenity Avatar answered Sep 21 '22 15:09

Serenity