I have this dataframe.
I've tried using ax.plot in order to make a line plot where the Year column is the x axis, and where each country serves as a different line in the plot.
I've attempted using reset_index, to no avail:
Please check this snippet. You can also achieve your result using 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()
Here is a way to create such a lineplot using seaborn. First some toy data are created with a similar format.
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
years = np.arange(2016, 2021)
num_countries = 10
num_years = len(years)
df = pd.DataFrame({'Country': np.repeat([f'country {i}' for i in range(1, num_countries + 1)], num_years),
'Year': np.tile(years, num_countries),
'Score': np.random.uniform(20, 50, num_years * num_countries)})
df.set_index(['Country', 'Year'], inplace=True)
df.reset_index(inplace=True)
fig, ax = plt.subplots(figsize=(12, 4))
sns.lineplot(x='Year', y='Score', hue='Country', data=df.reset_index(), ax=ax)
ax.set_xticks(years)
ax.legend(loc='upper left', bbox_to_anchor=[1.02, 1.02], ncol=2)
plt.tight_layout()
plt.show()