Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing the formatting of a datetime axis in matplotlib

Tags:

I have a series whose index is datetime that I wish to plot. I want to plot the values of the series on the y axis and the index of the series on the x axis. The Series looks as follows:

2014-01-01     7 2014-02-01     8 2014-03-01     9 2014-04-01     8 ... 

I generate a graph using plt.plot(series.index, series.values). But the graph looks like:

graph

The problem is that I would like to have only year and month (yyyy-mm or 2016 March). However, the graph contains hours, minutes and seconds. How can I remove them so that I get my desired formatting?

like image 788
Sheryl Avatar asked May 14 '17 21:05

Sheryl


People also ask

How do I format a date axis in Matplotlib?

Using the DateFormatter module from matplotlib, you can specify the format that you want to use for the date using the syntax: "%X %X" where each %X element represents a part of the date as follows: %Y - 4 digit year with upper case Y. %y - 2 digit year with lower case y. %m - month as a number with lower case m.

How do I change axis labels in Pyplot?

To set labels on the x-axis and y-axis, use the plt. xlabel() and plt. ylabel() methods.


2 Answers

import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates  # sample data N = 30 drange = pd.date_range("2014-01", periods=N, freq="MS") np.random.seed(365)  # for a reproducible example of values values = {'values':np.random.randint(1,20,size=N)} df = pd.DataFrame(values, index=drange)  fig, ax = plt.subplots() ax.plot(df.index, df.values) ax.set_xticks(df.index)  # use formatters to specify major and minor ticks ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m")) ax.xaxis.set_minor_formatter(mdates.DateFormatter("%Y-%m")) _ = plt.xticks(rotation=90)     

enter image description here

like image 69
andrew_reece Avatar answered Sep 21 '22 13:09

andrew_reece


You can try something like this:

import matplotlib.dates as mdates import matplotlib.pyplot as plt df = pd.DataFrame({'values':np.random.randint(0,1000,36)},index=pd.date_range(start='2014-01-01',end='2016-12-31',freq='M')) fig,ax1 = plt.subplots() plt.plot(df.index,df.values) monthyearFmt = mdates.DateFormatter('%Y %B') ax1.xaxis.set_major_formatter(monthyearFmt) _ = plt.xticks(rotation=90) 

enter image description here

like image 26
Scott Boston Avatar answered Sep 20 '22 13:09

Scott Boston