【问题标题】:Python/Pandas - How to Create a Line Graph in a multi-level pivoted tablePython/Pandas - 如何在多级透视表中创建折线图
【发布时间】:2021-04-18 10:25:07
【问题描述】:

我旋转了一个 DF,根据我想要的组织设置了索引。

但我无法创建 x 轴为年份和每个国家/地区及其价值的图表。为了展示每个国家的演变。

我尝试了 Seaborn 和 Matplotlib,但我无法做到。

我的 GitHub 链接:https://github.com/IgorComune/RenewableEnergy/blob/main/RenewableEnergy.ipynb


table = pd.pivot_table(top_20_average,index=['country','year'])
table

country     year    gerenation_renewables_per_capita
Austria     2000    5382.823150
            2001    5215.238330
            2002    5150.725350
            2003    4311.643836
            2004    4822.806377
        ... ... ...
Venezuela   2015    2467.522106
            2016    2090.616730
            2017    2039.997279
            2018    1995.568941
            2019    1827.675691
380 rows × 1 columns

【问题讨论】:

    标签: python pandas matplotlib seaborn pivot-table


    【解决方案1】:

    使用 seaborn,使用显式列是最简单的。 Pandas 的reset_index() 将索引转换为常规列。下面是一个从测试数据开始的代码示例:

    from matplotlib import pyplot as plt
    import seaborn as sns
    import numpy as np
    import pandas as pd
    
    countries = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stu', 'vwx']
    years = np.arange(2000, 2021)
    df = pd.DataFrame({'country': np.repeat(countries, len(years)),
                       'year': np.tile(years, len(countries)),
                       'value': (np.random.uniform(-100, 200, (len(countries), len(years))).cumsum(axis=1)
                                 + np.random.uniform(400, 1200, (len(countries), 1))).ravel()})
    table = pd.pivot_table(df, index=['country', 'year'])
    ax = sns.lineplot(data=table.reset_index(), x='year', y='value', hue='country', palette='husl')
    ax.set_xticks(years[::2])
    ax.margins(x=0)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2022-06-13
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多