Plotting using Pandas and datetime format

Viewed 19704

I have a dataframe with just two columns, Date, and ClosingPrice. I am trying to plot them using df.plot() but keep getting this error:

ValueError: view limit minimum -36785.37852 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units

I have found documentation about this from matplotlib but that says how to make sure that the format is datetime. Here is code that I have to make sure the format is datetime and also printing the data type for each column before attempting to plot.

df.Date = pd.to_datetime(df.Date)

print(df['ClosingPrice'].dtypes)
print(df['Date'].dtypes)

The output for these print statements are:

float64 datetime64[ns]

I am not sure what the problem is since I am verifying the data type before plotting. Here is also what the first few rows of the data set look like:

Date ClosingPrice 0 2013-09-10 64.7010 1 2013-09-11 61.1784 2 2013-09-12 61.8298 3 2013-09-13 60.8108 4 2013-09-16 58.8776 5 2013-09-17 59.5577 6 2013-09-18 60.7821 7 2013-09-19 61.7788 Any help is appreciated.

2 Answers

EDIT 2 after seeing more people ending up here. To be clear for new people to python, you should first import pandas for the codes bellow to work:

import pandas as pd

EDIT 1: (short quick answer)

If³ you don't want to drop your original index (this makes sense after reading the original and long answer bellow) you could:

df[['Date','ClosingPrice']].plot('Date', figsize=(15,8))

Original and long answer:

Try setting your index as your Datetime column first:

df.set_index('Date', inplace=True, drop=True)

Just to be sure, try setting the index dtype (edit: this probably wont be needed as you did it previously):

df.index = pd.to_datetime(df.index)

And then plot it

df.plot()

If this solves the issue it's because when you use the .plot() from DataFrame object, the X axis will automatically be the DataFrame's index.

If² your DataFrame had a Datetimeindex and 2 other columns (say ['Currency','pct_change_1']) and you wanted to plot just one of them (maybe pct_change_1) you could:

# single [ ] transforms the column into series, double [[ ]] into DataFrame
df[['pct_change_1']].plot(figsize=(15,8)) 

Where figsize=(15,8) you're setting the size of the plot (width, height).

Here is a simple solution:

  my_dict = {'Date':['2013-09-10', '2013-09-11', '2013-09-12', '2013-09-13', '2013-09-16', '2013-09-17', '2013-09-18',
     '2013-09-19'], 'ClosingPrice': [ 64.7010, 61.1784, 61.8298, 60.8108, 58.8776, 59.5577, 60.7821, 61.7788]}

  df = pd.DataFrame(my_dict)
  df.set_index('Date', inplace=True)
  df.plot()
Related