7
import pandas as pd
import numpy as np

import matplotlib.pyplot as plt

dates = np.arange(1990,2061, 1)
dates = dates.astype('str').astype('datetime64')

df = pd.DataFrame(np.random.randint(0, dates.size, size=(dates.size,3)), columns=list('ABC'))
df['year'] = dates

cols = df.columns.tolist()
cols = [cols[-1]] + cols[:-1]
df = df[cols]

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

ax.stackplot(df['year'], df.drop('year',axis=1))

Based on this code, I'm getting an error "TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''"

I'm trying to figure out how to plot a DataFrame object with years in the first column, and then stacked area from the subsequent columns (A, B, C)..

Also, since I'm a complete beginner here... feel free to comment on my code as to make it cleaner / better. I understand that if I use Matplotlib instead of the Pandas integrated plot method, that I have more functionality to adjust things later on?

Thanks!

1 Answer 1

17

I run into two problems running your code.

First, stackplot seems to dislike using string representations of dates. Datetime data types are very finicky sometimes. Either use integers for your 'year' column, or use .values to convert from pandas to numpy datatypes as described in this question

Secondly, according to the documentation for stackplot, when you call stackplot(x, y) if x is a Nx1 array, then y must be MxN, where M is the number of columns. Your df.drop('year',axis=1)) will end up as NxM and throw another error at you. If you take the transpose, however, you can make it work.

If I just replace your final line with

ax.stackplot(df['year'].values, df.drop('year',axis=1).T)

I get a plot that looks like this:

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Wow. Good reading and also appreciate your insights to the problem!
OMG. THANK YOU! You saved me a lot of confusion. Pandas and dataframes are wonderful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.