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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With