Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib boxplot width in log scale

I am trying to plot a boxplot with logarithmic x-axis. As you can see on the example below width of each box decreases because of the scale. Is there any way to make the width of all boxes same?

enter image description here

like image 540
Tomas Avatar asked Dec 24 '22 13:12

Tomas


1 Answers

You can set a specific width of the box depending on the location on the plot. The boxplot's width argument allows to set different widths. To calculate the respective width, you need to transform the position to linear scale, add or subtract some linear width, and transform back to log scale. The difference between the two hence obtained values is the width of the bar to set.

The linear width w used here is of course somehow arbitrary; you need to select a good value for yourself.

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(42)

a = np.cumsum(np.random.rayleigh(150, size=(50,8)), axis=1)

fig, ax=plt.subplots()

positions=np.logspace(-0.1,2.6,8)

w = 0.1
width = lambda p, w: 10**(np.log10(p)+w/2.)-10**(np.log10(p)-w/2.)

ax.boxplot(a, positions=positions, widths=width(positions,w))
ax.set_xscale("log")
plt.show()

enter image description here

like image 173
ImportanceOfBeingErnest Avatar answered Jan 09 '23 16:01

ImportanceOfBeingErnest