【问题标题】:Plot a grouped by data frame绘制按数据框分组
【发布时间】:2019-03-03 20:18:00
【问题描述】:

我有这个要绘制的数据框。我有更多的国家、年份和变量。我只是粘贴其中的一部分作为示例。

                       gdp_share    military_exp
year    Country                     
2010    USA            5.0  768465792.0
        China          2.0  138028416.0 
        Korea          3.0  31117330.0  
        Russia         4.0  43120560.0  
2011    USA            5.0  758988352.0
        China          2.0  149022400.0
        Korea          3.0  31543720.0
        Russia         3.0  46022120.0

我使用data = data.set_index(["year", "Country"]) 按年份和国家/地区对其进行索引。

我也试过了:

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

但这没有用。它不断抛出这个错误:AttributeError: 'DataFrame' object has no attribute 'year'

有没有办法绘制一个折线图,其中每个国家/地区每年的折线仅在 y 轴上显示 gdp_share 列?

【问题讨论】:

    标签: pandas dataframe matplotlib indexing pandas-groupby


    【解决方案1】:

    试试这个:

    df.unstack('Country')['gdp_share'].plot()
    

    输出:

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 2022-08-16
      • 2018-05-17
      • 1970-01-01
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      • 2019-12-14
      • 2020-03-01
      相关资源
      最近更新 更多