我正在沿两个不同的轴绘制多个箱线图。 我的代码如下所示:
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 轴的 xlabel 相同且一致。
有什么想法吗?
这应该适用于您的示例代码。然而,这个解决方案绕过了
sharex
对齐
在我看来,使用箱线图和
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)
对于其他人,还可以查看
positions
所采用的 matplotlib.pyplot.boxplot()
参数。使用它,我们可以指定该图中每个箱线图的自己的位置。