如何将pandas列列表传递给pyplot图表?
这是我的代码,运行得还不错:
df = pd.DataFrame({
'foo' : [1, 2, 7, 2],
'bar' : [3, 1, 3, 2],
'spam' : [5, 2, 1, 0]
})
x = range(len(df.foo))
fig, ax = plt.subplots()
ax.stackplot(x, df.foo, df.bar, df.spam)
# plt.savefig('stackedarea.png')
plt.show()
我想问的是,怎么能传一个列表,这样就不用一个个写出每一列(比如 Df.foo, df.bar...)?
我对 lambda 函数和列表推导式还很陌生,我觉得可能需要用到其中之一。
(1) 我第一个想法是,传一个列名的列表:
columnlist = ['foo', 'bar']
# snip
ax.stackplot(x, #something_goes_here) #I tried df[columnlist[, no joy
(2) 我第二个想法是,传一个列的列表:
columnlist = ['foo', 'bar']
#here is where I don't know how to transform column list so it becomes
# passedlist, where passedlist = [df.foo, df.bar]
# snip
ax.stackplot(x, df[columnlist])
希望我解释得够清楚。我才学 Python 几个星期,请不要大声嘲笑我!
1 个回答
6
如果你想绘制所有的列,可以这样做:
ax.stackplot(x, *[ts for col, ts in df.iteritems()])
如果只想绘制一部分列:
ax.stackplot(x, *[df[col] for col in ['foo', 'bar']])
注意上面代码中的 *
符号。
补充说明:你还可以把一个二维数组传给 stackplot
,这样写会更简单:
ax.stackplot(x, df.T) # all columns
ax.stackplot(x, df[['foo','bar']].T) # only foo & bar columns