4

I'm trying to plot timeseries revenue data by quarter with matplotlib.pyplot but keep getting an error. Below is my code and the errors The desired behavior is to plot the revenue data by quarter using matplotlib. When I try to do this, I get:

TypeError: Axis must havefreqset to convert to Periods

Is it because timeseries dates expressed as periods cannot be plotted in matplotlib? Below is my code.

def parser(x):
    return pd.to_datetime(x, format='%m%Y')
tot = pd.read_table('C:/Desktop/data.txt', parse_dates=[2], index_col=[2], date_parser=parser)

tot = tot.dropna()
tot = tot.to_period('Q').reset_index().groupby(['origin', 'date'], as_index=False).agg(sum)

tot.head() 
origin  date    rev
0   KY  2016Q2  1783.16
1   TN  2014Q1  32128.36
2   TN  2014Q2  16801.40
3   TN  2014Q3  33863.39
4   KY  2014Q4  103973.66

plt.plot(tot.date, tot.rev)
oammon
  • 189
  • 1
  • 4
  • 12
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [mcve]. – ImportanceOfBeingErnest May 21 '17 at 18:35
  • i've added additional context – oammon May 21 '17 at 18:53

2 Answers2

6

If you want to use matplotlib, the following code should give you the desired plot:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({'origin': ['KY','TN','TN','TN','KY'],
                     'date': ['2016Q2','2014Q1','2014Q2','2014Q3','2014Q4'],
                      'rev': [1783.16, 32128.36, 16801.40, 33863.39, 103973.66]})
x = np.arange(0,len(df),1)
fig, ax = plt.subplots(1,1)
ax.plot(x,df['rev'])
ax.set_xticks(x)
ax.set_xticklabels(df['date'])
plt.show()

enter image description here

You could use the xticks command and represent the data with a bar chart with the following code:

plt.bar(range(len(df.rev)), df.rev, align='center')
plt.xticks(range(len(df.rev)), df.date, size='small')

enter image description here

0

It seems like bug.

For me works DataFrame.plot:

ooc.plot(x='date', y='rev')
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • you're using pandas to plot it. the version i posted is a simplified version, but i'm trying to understand whether there's a way to plot it with matplotlib. – oammon May 21 '17 at 18:46