I create 2 figures. One is a Seaborn figure and one is a matplotlib figure. Now I would like to combined those 2 figures into 1 combined figure. While the matplotlib figure is being displayed on the left hand side, the seaborn figure is not displayed. Here is the code
#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()
When running the code I get the following error "AttributeError: 'numpy.ndarray' object has no attribute 'xaxis'". The single seaborn figure is created and the combined matplotlib figure is also created. But only on the left side you can see the correct matplotlib figure while on the right side it is just empty.
Any ideas how I can do this?
CodePudding user response:
Some hopefully clarifying comments:
A figure is the top-level container for all plot elements. It's misleading/incorrect to refer to a matplotlib figure or seaborn figure, when really you're referring to an Axes
.
This creates one figure with two subplots.
fig, ax = plt.subplots(1,2, figsize=(12,6))
Pure matplotlib plotting:
ax[0].plot(X1, histogram_dist_train.pdf(X1), label='train'))
Seaborn plotting: passing an existing Axes
to kdeplot
:
sns.kdeplot(data=data_train.squeeze(), color='cornflowerblue', label='train', fill=False, ax=ax[1])