如何为 Seaborn 地块添加标题?
在本文中,我们将讨论如何在Python中为 Seaborn Plots 添加标题。
方法一:使用set方法添加title
set方法将 1 个参数“ title ”作为存储绘图标题的参数。
句法
set(title=”Title of a plot”)
示例:
在这里,我们将创建一个包含月份和平均温度的数据框
Python3
# import necessary packages
import pandas as pd
import seaborn as sns
# create a dataframe
temperature = pd.DataFrame({'Month': ['Jan', 'Feb', 'Mar',
'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'],
'Avg_Temperatures': [22, 25, 28,
32, 35, 44,
38, 32, 25,
23, 20, 18]})
# plot a line plot and set title
sns.lineplot(x='Month', y='Avg_Temperatures', data=temperature).set(
title="Monthly Avg Temperatures")
Python3
# import necessary packages
import pandas as pd
import seaborn as sns
# create a dataframe
temperature = pd.DataFrame({'Month': ['Jan', 'Feb', 'Mar',
'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'],
'Avg_Temperatures': [22, 25, 28,
32, 35, 44,
38, 32, 25,
23, 20, 18]})
# plot a rel-plot
plot = sns.relplot(x='Month', y='Avg_Temperatures', data=temperature)
# add title using suptitle
plot.fig.suptitle('Monthly Avg Temperatures')
Python3
# import necessary packages
import pandas as pd
import seaborn as sns
# create a dataframe
temperature = pd.DataFrame({'Month': ['Jan', 'Feb', 'Mar',
'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'],
'Avg_Temperatures': [22, 25, 28,
32, 35, 44,
38, 32, 25,
23, 20, 18]})
# plot a bar plot and add title using set_title
plot = sns.barplot(x='Month', y='Avg_Temperatures',
data=temperature).set_title('Monthly Avg Temperatures')
输出
方法2:使用suptitle方法添加标题
suptitle方法接受一个字符串,它是绘图的标题作为参数。
句法
fig.suptitle(‘Title of plot’)
示例:
Python3
# import necessary packages
import pandas as pd
import seaborn as sns
# create a dataframe
temperature = pd.DataFrame({'Month': ['Jan', 'Feb', 'Mar',
'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'],
'Avg_Temperatures': [22, 25, 28,
32, 35, 44,
38, 32, 25,
23, 20, 18]})
# plot a rel-plot
plot = sns.relplot(x='Month', y='Avg_Temperatures', data=temperature)
# add title using suptitle
plot.fig.suptitle('Monthly Avg Temperatures')
输出
方法三:使用 set_title 添加标题
set_title方法接受一个字符串作为参数,它是绘图的标题。
句法
set_title(‘Title of plot’)
示例:
Python3
# import necessary packages
import pandas as pd
import seaborn as sns
# create a dataframe
temperature = pd.DataFrame({'Month': ['Jan', 'Feb', 'Mar',
'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'],
'Avg_Temperatures': [22, 25, 28,
32, 35, 44,
38, 32, 25,
23, 20, 18]})
# plot a bar plot and add title using set_title
plot = sns.barplot(x='Month', y='Avg_Temperatures',
data=temperature).set_title('Monthly Avg Temperatures')
输出