Matplotlib,沿x轴移动框线图吗? [英] Matplotlib, shift boxplots along x-axis?

查看:113
本文介绍了Matplotlib,沿x轴移动框线图吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am plotting multiple boxplots along two different axes. My code looks like:

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)

这会生成一个图(代入我的实际数据),看起来像:

This produces a plot (substituting in my actual data) that looks like:

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

However, I would like the lower plot (on ax2) to shift to the right along the x-axis by one unit. That is, I would like to have the 2 lower boxplots plot at x=2 and x=3, such that they line up with the 2nd and 3rd upper boxplots. I would like to keep the xlabels the same and consistent for all x-axes.

有任何想法吗?

推荐答案

这应适用于您的示例代码。但是,此解决方案绕过了 sharex 资格

This should work for your example code. However this solution bypasses the sharex aligment

在我看来,使用箱形图和 sharex 有点不直观。

In my opinion, the axis labeling when using box plots and sharex is a little unintuitive.

%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)

这篇关于Matplotlib,沿x轴移动框线图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆