【问题标题】:How to plot grouped dataframe for multiple years and countries?如何绘制多年和国家的分组数据框?
【发布时间】:2019-02-26 15:53:39
【问题描述】:

这是我正在处理的分组数据帧。我有几个国家和年份的几个变量。如何使用 matplotlib 绘制折线图,​​显示不同国家/地区的变量“gdp_share”随时间的演变?

我使用以下方法对 DataFrame 进行了分组:

data = data.groupby(["year", "Country"]).mean()


              gdp_share military_exp    pop gdp gdp_pc  military_pc
year    Country                     
2010    China   2.0 138028416.0 1359755 13615620000 10226.87    101.509769
        France  2.0 54569820.0  63027   2559460000  39449.38    865.816555
        Germany 1.0 41488240.0  80895   3587004000  43928.90    512.865319
        Israel  6.0 15044490.0  7426    241692000   32665.37    2025.921088
2011    China   2.0 149022400.0 1367480 14957177000 11180.83    108.975927
        France  2.0 53235512.0  63344   2612677000  40078.52    840.419172
        Germany 1.0 40301428.0  80934   3718288000  45633.17    497.954234
        Israel  6.0 15582490.0  7569    254299000   33733.19    2058.725063
2012    China   2.0 161796896.0 1375199 16211650000 12058.70    117.653442
        France  2.0 52499752.0  63640   2617451000  39961.04    824.948963
        Germany 1.0 41262500.0  81066   3736582000  45771.68    508.998840
        Israel  6.0 15728390.0  7699    259884000   33840.45    2042.913365

【问题讨论】:

    标签: pandas dataframe matplotlib pandas-groupby


    【解决方案1】:

    试试

    fig, ax = plt.subplots()
    ax.set_xticks(data.year.unique())
    data.groupby(["year", "Country"]).mean()['gdp_share'].unstack().plot(ax=ax)
    

    【讨论】:

    • 考虑包含您的代码的简短描述
    • 它一直抛出这个错误:'DataFrame' object has no attribute 'year'
    • 怎么回事?你有列year。那么data.year 不会引发错误。
    • 我再次运行了所有单元格,这是现在的错误.. Empty 'DataFrame': no numeric data to plot
    • 这很奇怪,因为我确保将所有数字都转换为浮点数:for col in data.select_dtypes('object').columns: data[col] = pd.to_numeric(data[col], errors = 'coerce', downcast='float')
    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多