Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting using Pandas and datetime format

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.

like image 286
MathPhiz Avatar asked Sep 10 '18 22:09

MathPhiz


People also ask

What is datetime format pandas?

By default pandas datetime format is YYYY-MM-DD ( %Y-%m-%d ).

How do I change the date format in Matplotlib?

MatPlotLib with Python Create a figure and a set of subplots using subplots() method. Plot the dataframe using plot method, with df's (Step 1) time and speed. To edit the date formatting from %d-%m-%d to %d:%m%d, we can use set_major_formatter() method. Set the formatter of the major ticker.


1 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).

like image 124
mrbTT Avatar answered Oct 28 '22 11:10

mrbTT