- 在每个组中,使用
ax = fig.add_subplot(3, 2, 1, projection='3d') 创建一个ax,然后使用ax = plt.axes(projection='3d') 重新分配变量;这不会映射到ax。
- 要绘制到特定轴,请在绘图方法中使用
ax 参数
sns.histplot(df['freq: 1x'], ax=ax)
- 另外,将 seaborn 升级到 0.11 版,因为
sns.distplot 已被 displot 或 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()
使用 matplotlib 网格规范
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()