André Pacheco
André Pacheco

Reputation: 1885

Setting different errors for pandas plot bar

I'm trying to plot a probability distribution using a pandas.Series and I'm struggling to set different yerr for each bar. In summary, I'm plotting the following distribution:

enter image description here

It comes from a Series and it is working fine, except for the yerr. It cannot overpass 1 or 0. So, I'd like to set different errors for each bar. Therefore, I went to the documentation, which is available here and here.

According to them, I have 3 options to use either the yerr aor xerr:

The case I need is the last one. In this case, I can use a DataFrame, Series, array-like, dict and str. Thus, I set the arrays for each yerr bar, however it's not working as expected. Just to replicate what's happening, I prepared the following examples:

First I set a pandas.Series:

import pandas as pd
se = pd.Series(data=[0.1,0.2,0.3,0.4,0.4,0.5,0.2,0.1,0.1],
 index=list('abcdefghi'))

Then, I'm replicating each case:

This works as expected:

err1 = [0.2]*9
se.plot(kind="bar", width=1.0, yerr=err1)

enter image description here

This works as expected:

err2 = err1
err2[3] = 0.5
se.plot(kind="bar", width=1.0, yerr=err1)

enter image description here

Now the problem: This doesn't works as expected!

err_up = [0.3]*9
err_low = [0.1]*9
err3 = [err_low, err_up]
se.plot(kind="bar", width=1.0, yerr=err3)

enter image description here

It's not setting different errors for low and up. I found an example here and a similar SO question here, although they are using matplotlib instead of pandas, it should work here.

I'm glad if you have any solution about that. Thank you.

Upvotes: 2

Views: 152

Answers (2)

André Pacheco
André Pacheco

Reputation: 1885

Based on @Quanghoang comment, I started to think it was a a bug. So, I tried to change the yerr shape, and surprisely, the following code worked:

err_up = [0.3]*9
err_low = [0.1]*9
err3 = [[err_low, err_up]]
print (err3)
se.plot(kind="bar", width=1.0, yerr=err3)

enter image description here

Observe I included a new axis in err3. Now it's a (1,2,N) array. However, the documentation says it should be (2,N).

In addition, a possible work around that I found was set the ax.ylim(0,1). It doesn't solve the problem, but plots the graph correctly.

Upvotes: 1

Quang Hoang
Quang Hoang

Reputation: 150735

Strangely, plt.bar works as expected:

err_up = [0.3]*9
err_low = [0.1]*9
err3 = [err_low, err_up]
fig, ax = plt.subplots()
ax.bar(se.index, se, width=1.0, yerr=err3)
plt.show()

Output:

enter image description here

A bug/feature/design-decision of pandas maybe?

Upvotes: 2

Related Questions