benawad
benawad

Reputation: 705

Trouble plotting pandas DataFrame

I have a pandas DataFrame that has 2 columns one of the columns is a list of dates in this format: '4-Dec-14' the other column is a list of numbers. I want to plot a graph with the dates on the x-axis and numbers that correspond with that date on the y-axis. Either a scatter plot or line graph. I was trying to follow the tutorial on Matplotlib http://matplotlib.org/users/recipes.html 'Fixing common date annoyances' but it will not accept my date format. When I try using the plot function it returns an error: ValueError: invalid literal for float(): 4-Dec-14. How would I change my date format so it will work. Or is there some other way I can plot this DataFrame. Thanks

Upvotes: 0

Views: 1958

Answers (2)

Laaaars
Laaaars

Reputation: 55

Try converting your datecolumn into a date index. Try something like this:

df.index=pd.to_datetime(df.yourdatecolumn,format='%d-%b-%y')

Then you should be able to plot your data as:

plt.plot(df.index, df.yournumbercolumn)

Upvotes: 1

joris
joris

Reputation: 139142

You should first convert the strings in the date column, to actual datetime values:

df['date'] = pd.to_datetime(df['date'])

Then you can plot it, either by setting the date as the index:

df = df.set_index('date')
df['y'].plot()

or by specifying x and y in plot:

df.plot(x='date', y='y')

Upvotes: 4

Related Questions