LJG
LJG

Reputation: 767

Enhancing a multiline plot with seaborn

I have the following dataframe df, which illustrates the trend of the population over the years:

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

I made a graph of the population trend in the various countries over the years. The code I used is:

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')

Now I want to improve the graph. Particularly:

How can I proceed?

Upvotes: 0

Views: 46

Answers (1)

Tranbi
Tranbi

Reputation: 12731

You can specify the legend and ticks properties:

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()

Output:

enter image description here

Upvotes: 1

Related Questions