使用 seaborn 增强多线图

Enhancing a multiline plot with seaborn

我有以下数据框df,它说明了多年来的人口趋势:

Year    Germany     France      Italy
2010    81802257    64658856    59190143
2011    80222065    64978721    59364690
2012    80327900    65276983    59394207
2013    80523746    65600350    59685227
2014    80767463    66165980    60782668
2015    81197537    66458153    60795612
2016    82175684    66638391    60665551
2017    82521653    66809816    60589445
2018    82792351    67026224    60483973
2019    83019213    67177636    59816673
2020    83166711    67320216    59641488
2021    83155031    67439599    59257566

我做了一张历年各国人口趋势图。我使用的代码是:

import seaborn as sns
import pandas as pd
import matplotlib.pyplot as plt
sns.lineplot(x='Year', y='value', hue='variable', marker='o', data=pd.melt(df, ['Year']))
plt.xlabel('Year')
plt.ylabel('Population')
plt.ticklabel_format(style='plain', axis='y')
plt.title('Population from 2010 to 2021')

现在我想改进图表。特别是:

我该如何继续?

您可以指定图例和刻度属性:

import seaborn as sns
import matplotlib.pyplot as plt
your_plot = sns.lineplot(x='Year', y='value', hue='variable', marker='o', data=pd.melt(df, ['Year']))
plt.xlabel('Year')
plt.ylabel('Population (in thousands)')
plt.ticklabel_format(style='plain', axis='y')
plt.title('Population from 2010 to 2021')

#1
plt.legend(loc=0, bbox_to_anchor=[1,1])

#2
plt.yticks(your_plot.get_yticks(), your_plot.get_yticks() / 1000)

#3 (Edit: adding rotation parameter to avoid overlap
plt.xticks(df['Year'], rotation=45)

# ensuring eveything fits on the figure:
plt.tight_layout()
plt.show()

输出: