【问题标题】:how to make stacked plots for dataframe with multiple index in python?如何在python中为具有多个索引的数据框制作堆叠图?
【发布时间】:2021-04-24 03:39:45
【问题描述】:

我有每周收集的贸易出口数据。我打算用matplotlib 制作堆积条形图,但管理具有多个索引的熊猫数据框几乎没有困难。我查看了this post,但无法得到我所期望的。任何人都可以建议在 python 中执行此操作的可能方法吗?似乎我进行了错误的数据聚合,我想我可能会使用for loop 来迭代年份,然后在每周的基础上制作堆积条形图。有谁知道如何在matplotlib 中使这更容易?有什么想法吗?

可重现的数据和我的尝试

import pandas as pd
import matplotlib.pyplot as plt

# load the data
url = 'https://gist.githubusercontent.com/adamFlyn/0eb9d60374c8a0c17449eef4583705d7/raw/edea1777466284f2958ffac6cafb86683e08a65e/mydata.csv'
df = pd.read_csv(url, parse_dates=['weekly'])
df.drop('Unnamed: 0', axis=1, inplace=True)

nn = df.set_index(['year','week'])
nn.drop("weekly", axis=1, inplace=True)

f, a = plt.subplots(3,1)
nn.xs('2018').plot(kind='bar',ax=a[0])
nn.xs('2019').plot(kind='bar',ax=a[1])
nn.xs('2020').plot(kind='bar',ax=a[2])
plt.show()
plt.close()

这个尝试对我不起作用。而不是像20182019,...这样明确选择年份,是否有更有效的方式为具有多个索引的数据框制作堆积条形图?有什么想法吗?

期望的输出

这是desired stacked bar plot for year of 2018 as an example

我应该如何获得我想要的堆积条形图?有更好的想法吗?

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    试试这个:

    nn.groupby(level=0).plot.bar(stacked=True)
    

    或防止年份作为 x 轴的元组:

    for n, g in nn.groupby(level=0):
        g.loc[n].plot.bar(stacked=True)
    

    在 cmets 中根据请求更新

    for n, g in nn.groupby(level=0):
        ax = g.loc[n].plot.bar(stacked=True, title=f'{n} Year', figsize=(8,5))
        ax.legend(loc='lower center')
    

    改变布局位置

    fig, ax = plt.subplots(1,3)
    axi = iter(ax)
    for n, g in nn.groupby(level=0):
        axs = next(axi)
        g.loc[n].plot.bar(stacked=True, title=f'{n}', figsize=(15,8), ax=axs)
        axs.legend(loc='lower center')
    

    【讨论】:

    • 这也会将2018 传递给x-ticks。所以标签会写成(2018,1),... 有没有直接的方法可以去掉它?
    • @ScottBoston 感谢更新的尝试。我们应该如何控制figsize,图例位置,并添加每年+一些字符串作为标题?
    • 不应该将figsize 传递给subplots
    • @QuangHoang 我认为你可以做到这一点。不过我不太确定。
    【解决方案2】:

    尝试使用loc 而不是xs

    f, a = plt.subplots(3,1)
    for x, ax in zip(nn.index.unique('year'),a.ravel()):
        nn.loc[x].plot.bar(stacked=True, ax=ax)
    

    【讨论】:

    • 这太棒了!我应该如何控制图例位置(在每个堆叠图的顶部添加一个)并添加每个不同的年份 + 一些字符串作为标题?另外,我们如何保持每个子图之间的距离?
    • 查看documentsubplots。您可以在 for 循环内为每个子图添加标题,例如ax.set_title('some title').
    • @Adam 你可以使用...plot.bar(stacked=True, ax=ax, title=f'{n} Year')
    猜你喜欢
    • 2020-11-25
    • 2019-05-08
    • 2022-01-03
    • 2021-09-27
    • 2019-02-16
    • 1970-01-01
    • 2019-04-08
    • 2015-06-06
    • 2019-09-01
    相关资源
    最近更新 更多