如何为 seaborn 绘图添加标题(带示例)
要向单个海洋图添加标题,可以使用.set()函数。
例如,以下是向箱线图添加标题的方法:
sns. boxplot (data=df, x=' var1 ', y=' var2 '). set (title=' Title of Plot ')
要将全局标题添加到海洋多面图,您可以使用.suptitle()函数。
例如,以下是如何向 relplot 添加全局标题:
#define relplot rel = sns. relplot (data=df, x=' var1 ', y=' var2 ', col=' var3 ') #add overall title to replot rel. fig . suptitle (' Overall Title ')
以下示例展示了如何在实践中使用这些功能。
示例 1:为单个 Seaborn 图添加标题
以下代码显示了如何向 Seaborn 箱线图添加标题:
import pandas as pd import seaborn as sns import matplotlib. pyplot as plt #create fake data df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19, 23, 25, 29], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4], ' team ': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B']}) #create boxplot sns. boxplot (data=df, x=' team ', y=' points '). set (title=' Points by Team ')
以下代码显示了如何向海洋散点图添加标题:
sns. scatterplot (data=df, x=' points ', y=' assists '). set (title=' Points vs. Assists ')
以下代码显示了如何向 Seaborn regplot 添加标题:
sns. regplot (data=df, x=' points ', y=' assists '). set (title=' Points vs. Assists ')
示例 2:向 Seaborn 人脸图添加全局标题
以下代码显示了如何向 Seaborn 分面图添加标题:
import pandas as pd import seaborn as sns import matplotlib. pyplot as plt #create fake data df = pd. DataFrame ({' points ': [25, 12, 15, 14, 19, 23, 25, 29], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4], ' team ': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B']}) #create relplot rel = sns. relplot (data=df, x=' points ', y=' assists ', col=' team ') #add overall title rel. fig . suptitle (' Stats by Team ')
我们还可以使用subplots_adjust()参数将整体标题稍微移高,这样就不会干扰单个图:
#create relplot rel = sns. relplot (data=df, x=' points ', y=' assists ', col=' team ') #move overall title up rel. fig . subplots_adjust (top= .8 ) #add overall title rel. fig . suptitle (' Stats by Team ')