Python/Pandas - 如何在多级透视中创建折线图 table
Python/Pandas - How to Create a Line Graph in a multi-level pivoted table
我旋转了一个DF,按照我想要的组织设置索引。
但我无法创建一个图表,其中 x 轴为年份,每个国家/地区都有其价值。为了展示每个国家的演变。
我尝试了 Seaborn 和 Matplotlib,但我无法做到。
我的GitHub的link: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
使用 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()
我旋转了一个DF,按照我想要的组织设置索引。
但我无法创建一个图表,其中 x 轴为年份,每个国家/地区都有其价值。为了展示每个国家的演变。
我尝试了 Seaborn 和 Matplotlib,但我无法做到。
我的GitHub的link: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
使用 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()