Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw an errorplot and a boxplot sharing x and y axes

I am used to read programming documentation but I have to admit that when it comes to matplotlib, I get really lost & confused. I just want to draw 2 sets of data that share the same y and x Axes, but one set drawn as a boxplot, and the other as errorbars. I've tried setting hold to true or cloning the X axes but every time only one of the dataset gets drawn. Could someone share a simple code I could mimic ?

here is what I basically do

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax =  ax1.twinx()
ax.errorbar( ... )
ax =  ax1.twinx()
ax.boxplot(...)
plt.show()

My question is really similar to that one add boxplot to other graph in python which answer doesn't work.

Best regards

like image 867
mattator Avatar asked Oct 28 '25 07:10

mattator


2 Answers

You can absolutely do this, and you don't need to do anything special like make multiple x or y axes; since you want to plot them both on the same set of axes, you don't have to change anything.

One thing that you need to keep in mind is that the x-axis of a boxplot is range(1, num_boxes + 1), which might not be what you expect.

Here's an example using random data.

x = np.arange(4)
y = np.random.randn(20, 4)
plt.boxplot(y)
plt.errorbar(x, np.mean(y, axis=0), yerr=np.std(y, axis=0))

Error bar and boxplot

It may be difficult to see that this is working, but if you offset the x values you'll see that it is drawing error bars.

plt.boxplot(y)
plt.errorbar(x + 0.5, np.mean(y, axis=0), yerr=np.std(y, axis=0))

Offset

Finally, you can add 1 to x to get what you are probably wanting.

plt.boxplot(y)
plt.errorbar(x + 1, np.mean(y, axis=0), yerr=np.std(y, axis=0))

Looks okay

like image 72
tbekolay Avatar answered Oct 30 '25 07:10

tbekolay


Not sure why you are calling twinx every time, I think you just want to do:

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.errorbar( ... )
ax.boxplot(...)
plt.show()
like image 23
tacaswell Avatar answered Oct 30 '25 06:10

tacaswell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!