Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a stacked area plot in python with a Pandas DataFrame

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!

like image 437
bpdronkers Avatar asked Dec 13 '22 20:12

bpdronkers


1 Answers

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

like image 170
A. Entuluva Avatar answered Apr 30 '23 21:04

A. Entuluva