首页 > 解决方案 > 如何将在函数内创建的 seaborn 图添加到我在外部创建的 matplotlib 子图对象

问题描述

我像这样创建子图对象:

fig, ax = plt.subplots(2, 2, sharex=True, sharey=True, figsize=(18, 10))

然后调用我的自定义函数,在其中创建一个像这样的 seaborn 散点图:

prediction_plot(real_val=y_test,predic_val=y_predict,ax_lim_low=0.1,ax_lim_high=1,majr_tick=0.1,mnr_tick=0.05,ax_label='Mean Value')

在自定义函数中,我设置了各种美学属性并绘制了如下图:

graph=sns.regplot(data=df, x="actual", y="predicted",ci=95,x_bins=40, scatter_kws={"color": "black",'s':50},
                  line_kws={"color": "black"})

标签: pythonmatplotlibseaborn

解决方案


我看到在您创建 sns.regplot 的行中,您没有为它指定任何轴。

我不知道您在自定义函数中还做了什么,但您可以将子图轴传递给您的函数,如下所示:

prediction_plot(axis= ax, real_val=y_test,predic_val=y_predict,ax_lim_low=0.1,ax_lim_high=1,majr_tick=0.1,mnr_tick=0.05,ax_label='Mean Value')

然后在您的函数中,您可以将这些轴分配给 seaborn.regplot,如下所示:

graph=sns.regplot(data=df, x="actual", y="predicted",ci=95,x_bins=40, scatter_kws={"color": "black",'s':50},
                  line_kws={"color": "black"}, ax = ax)

推荐阅读