【问题标题】:How to plot figures to different subplot axes in matplotlib如何在 matplotlib 中将图形绘制到不同的子图轴
【发布时间】:2020-10-06 16:43:49
【问题描述】:

我试图用一个 3d 子图和 3 个 2d 子图的组合来绘制一个图形。为什么它们会相互重叠?

这是我的代码:

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()

【问题讨论】:

    标签: python matplotlib subplot


    【解决方案1】:
    • 在每个组中,使用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 已被 displothistplot 弃用。
    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()
    

    【讨论】:

      猜你喜欢
      • 2016-11-08
      • 1970-01-01
      • 2013-08-12
      • 1970-01-01
      • 2020-05-10
      • 2019-12-10
      • 1970-01-01
      • 2020-05-06
      • 2020-03-16
      相关资源
      最近更新 更多