【问题标题】:Pandas - Graphing Unstacked DataFrame with Multiple ColumnsPandas - 用多列绘制未堆叠的 DataFrame
【发布时间】:2016-11-02 22:43:12
【问题描述】:

我在 Pandas 中有一个 DataFrame,拆开时看起来像这样

     Unique Sessions
Date      2016-06-21 2016-06-29
Name
ABCD             995      4,088
EFGH               8         25
OPEF               1          1

如何让 Pandas 从此 DataFrame 中绘制堆积条形图,其中 x 轴是名称,y 轴是堆叠日期中的数字?

# df is the stacked DataFrame
plot = df.unstack().plot(kind='bar', stacked=True, title="Test")
plot.set_xlabel("Name")
plot.set_ylabel("Num")
plt.savefig('testplot.png', dpi=1000)

此代码将创建一个条形图,但仅考虑 2016-06-21 并且不会将 2016-06-29 的数字叠加到 21 日的数据之上。

【问题讨论】:

    标签: python python-3.x pandas matplotlib


    【解决方案1】:

    设置

    df = pd.DataFrame([[995, 4088], [8, 25], [1, 1]],
                      index=pd.Index(['ABCD', 'EFGH', 'OPEF'], name='Name'),
                      columns=pd.MultiIndex.from_product([['Unique Sessions'], ['2016-06-21', '2016-06-29']],
                                                         names=[None, 'Date']))
    
    print df
    
         Unique Sessions           
    Date      2016-06-21 2016-06-29
    Name                           
    ABCD             995       4088
    EFGH               8         25
    OPEF               1          1
    

    我做了什么

    plot = df['Unique Sessions'].plot.bar(stacked=True, title="Test")
    plot.set_xlabel("Name")
    plot.set_ylabel("Num")
    

    【讨论】:

    • 嗯,很奇怪。它不适用于我的桌子,但当我手动放入您的桌子时它可以工作。
    • 只是一个想法...是 4,088 中的逗号吗?
    • 是的,他们修好了。刚刚将 thousands=',' 添加到我的 read_csv 行中,它就起作用了。谢谢!
    猜你喜欢
    • 2016-03-26
    • 2017-12-09
    • 2018-04-12
    • 2019-02-12
    • 2016-12-08
    • 2018-02-06
    • 2021-07-18
    相关资源
    最近更新 更多