Matplotlib,沿 x 轴移动箱线图?

Matplotlib, shift boxplots along x-axis?

我正在沿两个不同的轴绘制多个箱线图。 我的代码如下所示:

fig, (ax1, ax2) = plt.subplots(2, sharex=True, sharey=False)

data_1 = [array1, array2, array3]
ax1.boxplot(data_1, whis=[5,95], showfliers=True)

data_2 = [array4, array5]
ax2.boxplot(data_2, whis=[5,95], showfliers=True)
ax2.set_xlim(0,4)

这会生成如下图(替换为我的实际数据):

但是,我希望下图(在 ax2 上)沿 x 轴向右移动一个单位。也就是说,我想在 x=2 和 x=3 处绘制 2 个下部箱线图,以便它们与第二个和第三个上部箱线图对齐。我想让所有 x 轴的 xlabels 保持相同和一致。

有什么想法吗?

这应该适用于您的示例代码。但是这个解决方案绕过了 sharex aligment

在我看来,使用箱形图和 sharex 时的轴标记有点不直观。

%matplotlib inline
import matplotlib.pylab as plt
import numpy as np
np.random.seed(42)

# create random data
for i in range(1,6):
    x = np.random.rand(10)
    exec("array%s = x" % i)

widths = 0.3
fig, (ax1, ax2) = plt.subplots(2, sharex=True, sharey=False)

data_1 = [array1, array2, array3]
ax1.boxplot(data_1, widths=0.3, whis=[5,95], showfliers=True)

data_2 = [array4, array5]
positions = [2,3]
ax2.boxplot(data_2, positions=positions, widths=widths, whis=[5,95], showfliers=True)

ax2.set_xticks([1,2,3])
ax1.set_xticks([1,2,3])
ax2.set_xticklabels([1,2,3])

plt.xlim(0,4)