简体   繁体   English

使用 seaborn 增强多线 plot

[英]Enhancing a multiline plot with seaborn

I have the following dataframe df , which illustrates the trend of the population over the years:我有以下 dataframe 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

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:特别:

  • Delete the legend title and move the legend to the right of the chart.删除图例标题并将图例移动到图表的右侧。
  • On the y-axis I would like the population expressed in thousands (without 1e3 appearing above the axis).在 y 轴上,我希望以千表示的人口(没有 1e3 出现在轴上方)。 Should I divide the population by 1000 and change the name of the axis?我应该将人口除以 1000 并更改轴的名称吗?
  • On the x-axis I would like to see all the years and not just 2010, 2012, 2014, etc.在 x 轴上,我想查看所有年份,而不仅仅是 2010 年、2012 年、2014 年等。

How can I proceed?我该如何进行?

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
plt.xticks(df['Year'])

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

Output: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM