【问题标题】:Matplotlib Subplot issuesMatplotlib 子图问题
【发布时间】:2020-09-21 20:00:28
【问题描述】:

我正在努力将数据框中的不同数据列绘制到 3 个不同的子图中。

所有数据都落入第三个子图,没有数据落入第二个子图,以此类推

# Set up the axes with gridspec
fig = plt.figure(figsize=(10, 10))
grid = plt.GridSpec(2, 4, wspace=1.0, hspace=0.2)

fig_ax1 = fig.add_subplot(grid[0, :2])
fig_ax1.set_title('Graph 1')
fig_ax1 = df['VARIABLE A'].hist(bins=30, color='purple')


fig_ax2 = fig.add_subplot(grid[0, 2:])
fig_ax2.set_title('Graph 2')
fig_ax2 = df.plot.scatter(x='VARIABLE B',y='VARIABLE A', c='Red')

fig_ax3 = fig.add_subplot(grid[1, 0:])
fig_ax3.set_title('Graph 3')
fig_ax3 = df['VARIABLE B'].hist(bins=30, orientation='horizontal')

我认为这是我声明要绘制的数据的每个图表的最终声明。请问如何解决这个问题?

【问题讨论】:

    标签: matplotlib subplot


    【解决方案1】:

    您需要将 ax 作为参数传递给 pandas 绘图命令。默认情况下,pandas 使用“当前 ax”创建绘图。返回此ax 以便更轻松地进行调整。如果您事先已经创建了自己的ax,则需要将其作为ax= 参数传递。

    pandas 文档在 visualization chapter 的“定位多个轴”下对此进行了解释。

    from matplotlib import pyplot as plt
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'VARIABLE A': np.random.randn(100), 'VARIABLE B': np.random.randn(100)})
    
    fig = plt.figure(figsize=(10, 10))
    grid = plt.GridSpec(2, 4, wspace=1.0, hspace=0.2)
    
    fig_ax1 = fig.add_subplot(grid[0, :2])
    fig_ax1.set_title('Graph 1')
    df['VARIABLE A'].hist(bins=30, color='purple', ax=fig_ax1)
    
    fig_ax2 = fig.add_subplot(grid[0, 2:])
    fig_ax2.set_title('Graph 2')
    df.plot.scatter(x='VARIABLE B', y='VARIABLE A', c='Red', ax=fig_ax2)
    
    fig_ax3 = fig.add_subplot(grid[1, 0:])
    fig_ax3.set_title('Graph 3')
    df['VARIABLE B'].hist(bins=30, orientation='horizontal', ax=fig_ax3)
    
    plt.show()
    

    【讨论】:

    • 非常感谢 JohanC!做到了 - 很抱歉我之前无法理解 ax= 部分(当我徒劳地搜索答案时),但这现在很清楚了!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2015-02-10
    • 2017-06-15
    相关资源
    最近更新 更多