本文介绍了如何将平均线和中线添加到海运地块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
有没有办法将平均值和中位数与Seborn的displot相加?
penguins = sns.load_dataset("penguins")
g = sns.displot(
data=penguins, x='body_mass_g',
col='species',
facet_kws=dict(sharey=False, sharex=False)
)
基于Add mean and variability to seaborn FacetGrid distplots,我看到我可以定义FacetGrid并映射函数。我可以将自定义函数传递给displot吗?
尝试直接使用displot的原因是绘图开箱即用,无需调整刻度标签大小、轴标签大小等,并且在视觉上与我正在绘制的其他绘图一致。
def specs(x, **kwargs):
ax = sns.histplot(x=x)
ax.axvline(x.mean(), color='k', lw=2)
ax.axvline(x.median(), color='k', ls='--', lw=2)
g = sns.FacetGrid(data=penguins, col='species')
g.map(specs,'body_mass_g' )
推荐答案
- 不推荐直接使用
FacetGrid。相反,可以使用其他图形级方法,如seaborn.displotseaborn.FacetGrid.map使用图形级方法。- seaborn: Building structured multi-plot grids
- 测试于
python 3.8.11、pandas 1.3.2、matplotlib 3.4.3、seaborn 0.11.2
选项%1
- 使用
plt.而不是ax。- 在OP中,
vlines要为histplot创建ax,但这里的图形是在.map之前创建的。
- 在OP中,
penguins = sns.load_dataset("penguins")
g = sns.displot(
data=penguins, x='body_mass_g',
col='species',
facet_kws=dict(sharey=False, sharex=False)
)
def specs(x, **kwargs):
plt.axvline(x.mean(), c='k', ls='-', lw=2.5)
plt.axvline(x.median(), c='orange', ls='--', lw=2.5)
g.map(specs,'body_mass_g' )
选项2
- 此选项更详细,但更灵活,因为它允许从用于创建
displot的数据源以外的数据源访问和添加信息。
import seaborn as sns
import pandas as pd
# load the data
pen = sns.load_dataset("penguins")
# groupby to get mean and median
pen_g = pen.groupby('species').body_mass_g.agg(['mean', 'median'])
g = sns.displot(
data=pen, x='body_mass_g',
col='species',
facet_kws=dict(sharey=False, sharex=False)
)
# extract and flatten the axes from the figure
axes = g.axes.flatten()
# iterate through each axes
for ax in axes:
# extract the species name
spec = ax.get_title().split(' = ')[1]
# select the data for the species
data = pen_g.loc[spec, :]
# print data as needed or comment out
print(data)
# plot the lines
ax.axvline(x=data['mean'], c='k', ls='-', lw=2.5)
ax.axvline(x=data['median'], c='orange', ls='--', lw=2.5)
两个选项的输出
资源
- 另请参阅以下问题/答案,以了解将信息添加到海运FaceGrid的其他方式
- Draw a line at specific position/annotate a Facetgrid in seaborn
- Overlay a vertical line on seaborn scatterplot with multiple subplots
- How to add additional plots to a seaborn FacetGrid and specify colors
这篇关于如何将平均线和中线添加到海运地块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)