Skip to content
Advertisement

How to plot figures to different subplot axes in matplotlib

I was trying to plot a figure with a combination of a 3d subplot and 3 2d ones. Why do they overlap each other?

enter image description here

Here are my codes:

fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(3, 2, 1, projection='3d')
ax = plt.axes(projection='3d')
ax.scatter3D(extents[0], extents[1], extents[2], color='yellow')

ax = fig.add_subplot(3, 2, 2)
ax = sns.distplot(extents[0], color='red')
ax.set_title("Extent_0 Distribution")

ax = fig.add_subplot(3, 2, 4)
ax = sns.distplot(extents[1], color='blue')
ax.set_title("Extent_1 Distribution")

ax = fig.add_subplot(3, 2, 6)
ax = sns.distplot(extents[2], color='green')
ax.set_title("Extent_2 Distribution")

plt.show()

Advertisement

Answer

  • In each group, an ax is created with ax = fig.add_subplot(3, 2, 1, projection='3d'), but then you reassign the variable with ax = plt.axes(projection='3d'); this does not plot to ax.
  • To plot to a specific axes, use the ax parameter in the plot method
    • sns.histplot(df['freq: 1x'], ax=ax)
  • Also, upgrade seaborn to version 0.11, because sns.distplot is deprecated for displot or histplot.
import pandas as pd
import numpy as np  # for sample data

# sinusoidal sample data
sample_length = range(1, 3+1)
rads = np.arange(0, 2*np.pi, 0.01)
data = np.array([np.sin(t*rads) for t in sample_length])
df = pd.DataFrame(data.T, index=pd.Series(rads.tolist(), name='radians'), columns=[f'freq: {i}x' for i in sample_length])

# plot the figures and correctly use the ax parameter
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(3, 2, 1, projection='3d')
ax.scatter3D(df['freq: 1x'], df['freq: 2x'], df['freq: 3x'], color='green', s=5)

ax = fig.add_subplot(3, 2, 2)
sns.histplot(df['freq: 1x'], ax=ax)
ax.set_title("Extent_0 Distribution")

ax = fig.add_subplot(3, 2, 4)
sns.histplot(df['freq: 2x'], ax=ax)
ax.set_title("Extent_1 Distribution")

ax = fig.add_subplot(3, 2, 6)
sns.histplot(df['freq: 3x'], ax=ax)
ax.set_title("Extent_2 Distribution")

plt.tight_layout()

enter image description here

Using matplotlib gridspec

fig = plt.figure(constrained_layout=False, figsize=(10, 10))
gs1 = fig.add_gridspec(nrows=3, ncols=3)

ax1 = fig.add_subplot(gs1[:-1, :], projection='3d')
ax1.scatter3D(df['freq: 1x'], df['freq: 2x'], df['freq: 3x'], color='green', s=10)

ax2 = fig.add_subplot(gs1[-1, 0])
sns.histplot(df['freq: 1x'], kde=True, ax=ax2)
ax2.set_title("Extent_0 Distribution")

ax3 = fig.add_subplot(gs1[-1, 1])
sns.histplot(df['freq: 2x'], kde=True, ax=ax3)
ax3.set_title("Extent_1 Distribution")

ax4 = fig.add_subplot(gs1[-1, 2])
sns.histplot(df['freq: 3x'], kde=True, ax=ax4)
ax4.set_title("Extent_2 Distribution")

plt.tight_layout()

enter image description here

Advertisement