【问题标题】:How to pass a list of pandas columns to a pyplot chart?如何将熊猫列列表传递给 pyplot 图表?
【发布时间】:2014-03-15 14:54:05
【问题描述】:

这是我的代码,目前运行良好:

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几个星期,请不要大声窃笑!

【问题讨论】:

    标签: python matplotlib pandas


    【解决方案1】:

    如果你想绘制所有可以做的列:

    ax.stackplot(x, *[ts for col, ts in df.iteritems()])
    

    如果只是一个子集:

    ax.stackplot(x, *[df[col] for col in ['foo', 'bar']])
    

    注意上面几行中的*

    edit:你也可以将二维数组传递给stackplot,所以更简单的表示法是:

    ax.stackplot(x, df.T)  # all columns
    ax.stackplot(x, df[['foo','bar']].T)  # only foo & bar columns
    

    【讨论】:

    • 工作就像一个魅力!谢谢,我理解您综合列表中的列表理解。
    猜你喜欢
    • 1970-01-01
    • 2018-10-18
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    相关资源
    最近更新 更多