0

I am following this demo to use matplotlib.dates in order to add "ticks" per month using pandas series data. My pandas series is named weekly_data1991

Datetime
1991-01-08    2245
1991-01-09    2678 
1991-01-10    2987
1991-01-11    2258
....
Freq: W-SUN, dtype: int64

Unfortunately, this wipes out many of the "default" labels when just using straightforward matplotlib.pyplot.plot()

For example, if I use

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12,5))
plt.plot(weekly_data1991, color = 'green' )

I get in return enter image description here

Using matplotlib.dates,

from matplotlib import dates as mdates
fig = plt.figure(figsize=(12,5))
ax = plt.subplot(111)
plt.plot(weekly_data1991, color = 'green' )
years = mdates.YearLocator()
months = mdates.MonthLocator()
yearsFmt = mdates.DateFormatter('%Y')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_locator(months)
ax.grid(which='both', axis='x')
plt.show()

which outputs the plot

enter image description here

I can I put the labels back in?

2
  • you mean you want tick labels on the months as well? You probably need to set a minor_formatter as well Commented Dec 21, 2015 at 12:20
  • @tom I have tried monthsFmt = mdates.DateFormatter('%m) and ax.xaxis.set_major_formatter(monthsFmt) but that gets me nowhere Commented Dec 21, 2015 at 12:29

1 Answer 1

3

I find (Matplotlib 1.4.3) that I can get both major and minor tick labels formatted as dates using mdates.DateFormatter as follows.

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import dates as mdates

df = pd.read_csv('data.csv', sep=None, names=('Datetime', 'values'),
                 parse_dates=['Datetime'])

fig = plt.figure(figsize=(12,5))
ax = plt.subplot(111)
plt.plot(df['Datetime'], df['values'], color = 'green' )
years = mdates.YearLocator()
months = mdates.MonthLocator()
yearsFmt = mdates.DateFormatter('%Y')
monthsFmt = mdates.DateFormatter('%b')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_formatter(monthsFmt)
ax.xaxis.set_minor_locator(months)
ax.grid(which='both', axis='x')
for tick in ax.get_xaxis().get_major_ticks():
    tick.set_pad(15)
plt.show()

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.