Matplotlib boxplot x axis

2020-08-17 12:14发布

问题:

It's easier to ask this with a figure. At the moment i obtain the following boxplot graph using matplotlib:

Is there a way to obtain a figure like that, but with each box in a position coherent with the corresponding x-axis number (like in a normal scatter plot, but with boxes instead of points)?

At the moment the numbers on the x-axis are added by means of the labels= argument.

回答1:

You need to specify the positions argument to the boxplot constructor.

from matplotlib import pyplot as plt

plt.boxplot([[1,4],[2,5],[3,6]], positions=[2,4,5.5])

By default it uses the values [1, 2, ..., n] but you can specify a different x position for each bar and the xticks will be updated automatically.