Matplotlib, shift boxplots along x-axis?

被刻印的时光 ゝ 提交于 2019-12-11 09:27:32

问题


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:

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.

Any ideas?


回答1:


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

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)



来源:https://stackoverflow.com/questions/28712123/matplotlib-shift-boxplots-along-x-axis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!