使用Pandas DataFram在python中创建堆积面积图

2024-04-28 22:01:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

基于此代码,我得到一个错误“TypeError:ufunc'isfinite'不支持输入类型,并且无法根据强制转换规则“safe”将输入安全强制转换为任何支持的类型。”

我正试图找出如何在第一列中绘制一个数据帧对象,其中包含年份,然后从随后的列(a,B,C)中叠加区域。。

而且,因为我是这里的初学者。。。请随意评论我的代码,让它更干净/更好。我知道如果我使用Matplotlib而不是Pandas集成的plot方法,那么我以后有更多的功能来调整事情吗?

谢谢!


Tags: columns代码importdfsizeasnpfig
1条回答
网友
1楼 · 发布于 2024-04-28 22:01:50

我在运行代码时遇到两个问题。

首先,stackplot似乎不喜欢使用日期的字符串表示。日期时间数据类型有时非常挑剔。对“year”列使用整数,或者使用.values将pandas数据类型转换为this question中描述的numpy数据类型

其次,根据documentation for stackplot,当调用stackplot(x, y)时,如果x是Nx1数组,那么y必须是MxN,其中M是列数。你的df.drop('year',axis=1))最终将成为NxM并向你抛出另一个错误。然而,如果你接受了转置,你就可以让它工作。

如果我把你的最后一行换成

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

我得到的情节是这样的:

enter image description here

相关问题 更多 >