在 Matplotlib 中创建子图的子图时出现问题

Problem creating subplot of subplots in Matplotlib

我正在尝试使用 Matplotlib gridspec 创建子图的子图,即直方图上方的箱线图。我有一个 pandas 定量数据数据框。我有这个代码:

import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib.gridspec as gridspec

fig = plt.figure(figsize=(20, 20))
outer = fig.add_gridspec(6, 2, wspace=0.05, hspace=0.2)
a = 0

for i in range(6):
    for j in range(2):
        inner = outer[i, j].subgridspec(2, 1, wspace=0, hspace=0)
        axs = inner.subplots()
        
        for c, ax in np.ndenumerate(axs):
            sns.boxplot(data=data_quant, x=data_quant[data_quant.columns[a]], orient='h', ax=ax)
            data_quant[data_quant.columns[a]].hist(bins=50)
            ax.set(xticks=[])
            
        a += 1
        
plt.show()

这是结果: Histogram and boxplot

我的代码受此启发:但显然我没有得到相同的结果,即直方图颠倒并且箱线图太大。

关于如何操作的任何线索?

下面的代码包含以下更改:

  • 循环for c, ax in np.ndenumerate(axs):似乎两次绘制相同的两个子图。它已被在上方的子图上绘制箱线图并在下方绘制直方图所取代。
  • subgridspec的调用设置height_ratios让箱线图占据高度的15%。
  • inner.subplots() 现在有 sharex=True 所以两个 x 轴同步。
  • fig.add_gridspec(...) 设置更窄的边框(左、右、下、上)。
  • 已生成一些虚拟测试数据
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np

plt.style.use('ggplot')
data_quant = pd.DataFrame({col: np.random.randn(100, 10).cumsum(axis=0).ravel() for col in 'abcdefghijkl'})

fig = plt.figure(figsize=(20, 20))
outer = fig.add_gridspec(6, 2, wspace=0.05, hspace=0.2, left=0.03, right=0.98, bottom=0.03, top=0.98)
a = 0

for i in range(6):
    for j in range(2):
        inner = outer[i, j].subgridspec(2, 1, wspace=0, hspace=0, height_ratios=[0.15, 0.85])
        axs = inner.subplots(sharex=True)

        sns.boxplot(data=data_quant, x=data_quant[data_quant.columns[a]], orient='h', ax=axs[0])
        data_quant[data_quant.columns[a]].hist(bins=50, ax=axs[1])
        axs[1].set(xticks=[])
        # axs[1].invert_yaxis() # if you want the histogram upside down
        a += 1
plt.show()