Reputation: 2443
Here is my code, which works fine as far as it goes:
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()
My question is, how can I pass a list so I don't have to explicitly type out every column (Df.foo, df.bar...)?
I'm still a rank beginner at lambda functions and list comprehensions, I suspect one or the other is required.
(1) My first idea, to pass a list of column names
columnlist = ['foo', 'bar']
# snip
ax.stackplot(x, #something_goes_here) #I tried df[columnlist[, no joy
(2) My second idea, to pass a list of columns:
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])
Hopefully I've explained well enough. I've only been doing python for a few weeks, please don't snicker out loud!
Upvotes: 1
Views: 1595
Reputation: 77951
if you want to plot all the columns you can do:
ax.stackplot(x, *[ts for col, ts in df.iteritems()])
if only a subset:
ax.stackplot(x, *[df[col] for col in ['foo', 'bar']])
note the *
in above lines.
edit: you can also pass a 2-dimensional array to stackplot
, so the simpler notation is:
ax.stackplot(x, df.T) # all columns
ax.stackplot(x, df[['foo','bar']].T) # only foo & bar columns
Upvotes: 6