通过add_subplot添加子图后如何共享轴?

Cle*_*leb 5 python matplotlib pandas

我有一个这样的数据框:

df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd'))     

    A    B    C    D
a  0.3  0.1  0.2  0.6
b  0.2  0.0  0.5  0.3
c  0.5  0.3  0.0  0.4
d  0.2  0.1  0.7  0.6
Run Code Online (Sandbox Code Playgroud)

现在我想将每一行绘制为条形图,其中 y 轴和 x-tick-labels 使用add_subplot.

到目前为止,我只能生成一个如下所示的图: 在此处输入图片说明

有一个问题:

轴不共享,使用后如何做到这一点add_subplot在这里,这个问题是通过创建一个巨大的子图来解决的;有没有办法以不同的方式做到这一点?

我想要的结果看起来像上面的图,唯一的区别是上面一行没有 x-tick-labels,现在右列中有 y-tick-labels。

我目前的尝试如下:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd'))

fig = plt.figure()
bar_width = 0.35
counter = 1
index = np.arange(df.shape[0])

for indi, rowi in df.iterrows():

    ax = fig.add_subplot(2, 2, counter)
    ax.bar(index, rowi.values, width=bar_width, tick_label=df.columns)
    ax.set_ylim([0., 1.])
    ax.set_title(indi, fontsize=20)
    ax.set_xticks(index + bar_width / 2)
    counter += 1

plt.xticks(index + bar_width / 2, df.columns)
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 2

如何在 matplotlib 中生成共享子图的问题:

这里可能更有趣的是,您还可以直接使用 pandas 在一行中创建绘图:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'A': [0.3, 0.2, 0.5, 0.2], 'B': [0.1, 0.0, 0.3, 0.1], 'C': [0.2, 0.5, 0.0, 0.7], 'D': [0.6, 0.3, 0.4, 0.6]}, index=list('abcd'))
df.plot(kind="bar", subplots=True, layout=(2,2), sharey=True, sharex=True)
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述