Seaborn 从不同的数据帧创建两个线图,在几个块中使用这些图,然后将这些图组合到另一个块中

Seaborn to create two lineplots from different dataframes, reusing these plots in several chunks, and then combining these plots in another chunk

由此,我发现了如何重用绘图。

这是第一个情节

plot_depression, ax = plt.subplots() 
ax=sns.lineplot(x="time", 
            y="value", 
            hue = "Group",
            ci=90, err_style='bars',
            data=df_long)
ax.set(xlabel = "Time", ylabel = "Result")
ax.set_title('Trajectory of depression during the pandemic', size=20)

这是第二个情节

plot_anxiety, ax = plt.subplots() 
ax=sns.lineplot(x="time", 
            y="value", 
            hue = "Group",
            ci=90, err_style='bars',
            data=df_long2)
ax.set(xlabel = "Time", ylabel = "Result")
ax.set_title('Trajectory of anxiety during the pandemic', size=20)

在任何块中,我都可以通过调用 plot_depressionplot_anxiety 来重用这些图。 但是,当我尝试使用此 组合这两个图时,结果是两个空图

fig, ax = plt.subplots(1, 2)
plot_anxiety
plot_depression

感谢任何帮助。 如果需要完整的df,我可以编辑这个问题。

这个想法是让 1 个图形和 2 个子图。所以对 plt.subplots() 的调用应该只执行一次,并且您的绘图需要引用它的输出。

这是您需要做的事情:

fig, ax = plt.subplots(1,2)  # only do this 1x 

sns.lineplot(x="time", 
             y="value", 
             hue = "Group",
             ci=90, err_style='bars',
             data=df_long, ax=ax[0])  # use this as 1st plot in `fig`
ax[0].set(xlabel = "Time", ylabel = "Result")
ax[0].set_title('Trajectory of depression during the pandemic', size=20)

sns.lineplot(x="time", 
             y="value", 
             hue = "Group",
             ci=90, err_style='bars',
             data=df_long2, ax=ax[1])  # use this as 2nd plot in `fig`
ax[1].set(xlabel = "Time", ylabel = "Result")
ax[1].set_title('Trajectory of anxiety during the pandemic', size=20)

plt.show()