Pandas 制作多索引数据帧的matplotlib线图,每行具有不同的线,其索引用作X轴

Pandas 制作多索引数据帧的matplotlib线图,每行具有不同的线,其索引用作X轴,pandas,dataframe,matplotlib,Pandas,Dataframe,Matplotlib,我有这个数据框 我尝试使用ax.plot来绘制线条图,其中Year列是x轴,每个国家在图中作为不同的线条 我尝试使用重置索引,但无效: 以下是使用seaborn创建此类线图的方法。首先,使用类似的格式创建一些玩具数据 从matplotlib导入pyplot作为plt 作为pd进口熊猫 将numpy作为np导入 导入seaborn作为sns 年份=np.arange(2016年、2021年) 国家数量=10 年数=年数(年) df=pd.DataFrame({'Country':np.repea

我有这个数据框

我尝试使用
ax.plot
来绘制线条图,其中
Year
列是x轴,每个国家在图中作为不同的线条

我尝试使用
重置索引
,但无效:


以下是使用seaborn创建此类线图的方法。首先,使用类似的格式创建一些玩具数据

从matplotlib导入pyplot作为plt
作为pd进口熊猫
将numpy作为np导入
导入seaborn作为sns
年份=np.arange(2016年、2021年)
国家数量=10
年数=年数(年)
df=pd.DataFrame({'Country':np.repeat([f'Country{i}'表示范围(1,num_countries+1)],num_年),
“年”:np.tile(年,国家数量),
“分数”:np.random.uniform(20、50、num_年*num_国家)}
df.set_索引(['国家','年'],原地=真)
df.reset_索引(原地=真)
图,ax=plt.子批次(图尺寸=(12,4))
sns.lineplot(x='Year',y='Score',hue='Country',data=df.reset_index(),ax=ax)
ax.set_xticks(年)
ax.图例(loc='左上角',bbox_至_锚=[1.02,1.02],ncol=2)
plt.紧_布局()
plt.show()

请检查此片段。您还可以使用Matplotlib


如果这个或另一个答案是有用的,你可以考虑投票和/或答案。
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
idx = pd.MultiIndex.from_product([['Albania', 'Zimbabwe'],[2016,2017,2018,2019,2020]],names=['Country', 'Year'])
col = ['Score']
df = pd.DataFrame('-', idx, col)
df['Score']=[28.4,28.9,30,30.3,27.1,20,21.8,23.1,22.3,20]
fig, ax = plt.subplots(figsize=(5, 4))
df.reset_index().pivot('Year','Country','Score').plot(ax=ax, title='MultiIndex Plot', grid=True)
ax.legend(bbox_to_anchor=(0.675, 1.175),loc='upper left')
years = np.arange(2016, 2021)
ax.set_xticks(years)
plt.show()