python - 如何在 seaborn 的 lmplot 中添加比较线?
问题描述
我想结合我拥有的以下 lmplots。更具体地说,红线是每个季节的平均值,我想将它们与其他数据放在各自的 lmplots 上,而不是将它们分开。这是我的代码(注意,轴限制不起作用,因为第二个 lmplot 把它弄乱了。当我只绘制初始数据时它起作用):
ax = sns.lmplot(data=data, x='air_yards', y='cpoe',col='season', lowess = True, scatter_kws={'alpha':.6, 'color': '#4F2E84'}, line_kws={'alpha':.6, 'color': '#4F2E84'})
ax = sns.lmplot(data=avg, x='air_yards', y= 'cpoe',lowess=True, scatter=False, line_kws={'linestyle':'--', 'color': 'red'}, col = 'season')
axes.set_xlim([-5,30])
axes.set_ylim([-25,25])
ax.set(xlabel='air yards')
解决方案
不确定它是否可能是您想要的方式,所以可能是这样的:
import matplotlib.pyplot as plt
import seaborn as sns
#dummy example
data = pd.DataFrame({'air_yards': range(1,11),
'cpoe': range(1,11),
'season': [1,2,3,2,1,3,2,1,3,2]})
avg = pd.DataFrame({'air_yards': [1, 10]*3,
'cpoe': [2,2,5,5,8,8],
'season': [1,1,2,2,3,3]})
# need this info
n = data["season"].nunique()
# create the number of subplots
fig, axes = plt.subplots(ncols=n, sharex=True, sharey=True)
# now you need to loop through unique season
for ax, (season, dfg) in zip(axes.flat, data.groupby("season")):
# set title
ax.set_title(f'season={season}')
# create the replot for data
sns.regplot("air_yards", "cpoe", data=dfg, ax=ax,
lowess = True, scatter_kws={'alpha':.6, 'color': '#4F2E84'},
line_kws={'alpha':.6, 'color': '#4F2E84'})
# create regplot for avg
sns.regplot("air_yards", "cpoe", data=avg[avg['season'].eq(season)], ax=ax,
lowess=True, scatter=False,
line_kws={'linestyle':'--', 'color': 'red'})
plt.show()
推荐阅读
- kubernetes - Kubernetes API 服务器如何在节点上启动新调度的 Pod?
- c++ - CMake:使用项目安装 boost 组件库的正确方法
- react-native - 如何在 React Native 中获取截断的文本值?
- csv - 在bash中按名称(匹配模式)提取列
- python - 有效删除 pandas DataFrame 列中的相似字符串
- aws-lambda - AWS Lambda 上的 Puppeteer 目标关闭错误
- r - 在箱线图中添加线条,如何知道因子在 x 轴上的位置?
- sql - 从匹配模式 postgresql 的字符串中删除字符
- javascript - 在 javascript 中使用 mailchimp API 显示终端中的所有项目
- javascript - 为什么我的 Mongoose 用户导入无效?未捕获的 TypeError:分配给常量变量