Matplotlib 子图问题

Matplotlib Subplot issues

我正在努力将数据框中的不同数据列绘制成 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')

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

您需要将 ax 作为参数传递给 pandas 绘图命令。默认情况下,pandas 使用“当前轴”创建绘图。返回此 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()