Tiago Emanuel Pratas
Tiago Emanuel Pratas

Reputation: 463

Plot x-axis in months

I have a dataframe and want to plot it in months with the x-axis labeled in day-month format but it shows error.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter
%matplotlib inline

#import dataframe
d = {'values': [10, 5,2,1,4,5], 'dates': ['2013-10-09', '2013-11-20','2013-12-31','2014-01-25','2014-02-25','2014-03-25']}
df = pd.DataFrame(data=d)
df = df.set_index('dates')

#plot 

fig, ax = df['values'].plot(figsize=(16,8))

ax.set(xlabel="Date",
       ylabel="Value")

date_form = DateFormatter("%d-%m")

ax.xaxis.set_major_formatter(date_form)

plt.show()

enter image description here

I wished to have the x-axis in "day-month' format

Upvotes: 2

Views: 2436

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150785

There are two things in your code:

  1. Your index is string index, not datetime
  2. df.plot returns a single axis instance, you cannot unpack it to fig, ax

That said, this should work:

# convert index to datetime
df.index=pd.to_datetime(df.index)

# plot, return only axis instance
ax = df['values'].plot(figsize=(16,8))

ax.set(xlabel="Date",
       ylabel="Value")

date_form = DateFormatter("%d-%m")

ax.xaxis.set_major_formatter(date_form)

plt.show()

Output:

enter image description here

Upvotes: 2

Related Questions