如何将 matplotlib 图形和 seaborn 图形放入一个组合的 matplotlib 图形中

How to put a matplotlib figure and a seaborn figure into one combined matplotlib figure

我创建了 2 个数字。一个是 Seaborn 图,一个是 matplotlib 图。现在我想将这 2 个数字合并为 1 个组合数字。当左侧显示 matplotlib 图形时,不显示 seaborn 图形。这是代码

#Plot the seaborn figure
fig, ax = plt.subplots(figsize=(12,6))
sns.kdeplot(data=data_train.squeeze(), color='cornflowerblue', label='train', fill=False, ax=ax)
sns.kdeplot(data=data_valid.squeeze(),  color='orange', label='valid', fill=False, ax=ax)
sns.kdeplot(data=data_test.squeeze(),  color='green', label='test', fill=False, ax=ax)
ax.legend(loc=2, prop={'size': 20})
plt.tight_layout()
plt.xticks(fontsize =20)
plt.yticks(fontsize =20)
plt.title(f"{currentFeature}\nKernel density functions", fontsize = 20)
plt.ylabel('Density',fontsize=20)
plt.show()


# Plot a matplotlib figure in a combined plot on the left side
X1 = np.linspace(data_train.min(), data_train.max(), 1000)
X2 = np.linspace(data_valid.min(), data_valid.max(), 1000)
X3 = np.linspace(data_test.min(), data_test.max(), 1000)
fig, ax = plt.subplots(1,2, figsize=(12,6))
ax[0].plot(X1, histogram_dist_train.pdf(X1), label='train')
ax[0].plot(X2, histogram_dist_valid.pdf(X2), label='valid')
ax[0].plot(X3, histogram_dist_test.pdf(X3), label='test')
ax[0].set_title('matplotlib figure', fontsize = 14)
ax[0].legend()
#Try to plot the same seaborn figure from above on the right side of the combined figure
ax[1].plot(sns.kdeplot(data=data_train.squeeze(), color='cornflowerblue', label='train', fill=False, ax=ax))
ax[1].plot(sns.kdeplot(data=data_valid.squeeze(),  color='orange', label='valid', fill=False, ax=ax))
ax[1].plot(sns.kdeplot(data=data_test.squeeze(),  color='green', label='test', fill=False, ax=ax))
ax[1].set_title('seaborn figure', fontsize = 14)
ax[1].legend()

当 运行 代码出现以下错误“AttributeError:'numpy.ndarray' 对象没有属性 'xaxis'”。创建了单个 seaborn 图,还创建了组合的 matplotlib 图。但是只有在左边你可以看到正确的matplotlib图,而在右边它只是空的。

有什么办法可以做到这一点吗?

一些希望澄清的评论:

图形是所有绘图元素的 top-level 容器。 misleading/incorrect 指的是 matplotlib 图形或 seaborn 图形,而实际上你指的是 Axes

这将创建 一个 图和两个子图。

fig, ax = plt.subplots(1,2, figsize=(12,6))

纯 matplotlib 绘图:

ax[0].plot(X1, histogram_dist_train.pdf(X1), label='train'))

Seaborn 绘图:将现有的 Axes 传递给 kdeplot:

sns.kdeplot(data=data_train.squeeze(), color='cornflowerblue', label='train', fill=False, ax=ax[1])