Home > OS >  last bar is hiding behind in pandas grouped bar plot
last bar is hiding behind in pandas grouped bar plot

Time:11-12

I am plotting a grouped bar plot out of the data:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'x':[0.716468, 0.799652, 0.611284, 0.700020, 0.745372, 0.717280, 0.212407, 0.225291, 0.443395, 0.649912, 0.756463, 0.588992],
'y':[1.891988, 2.750937, 4.495497, 5.260436, 6.100882, 6.262784, 7.339279, 6.877465, 6.349050, 4.797649, 3.290293, 2.106541],
'x_err':[0.022882, 0.021447, 0.009402, 0.011324, 0.008872, 0.015882, 0.009615, 0.007617, 0.012816, 0.010310, 0.009213, 0.020137],
'y_err':[0.156298, 0.151681, 0.178215, 0.143700, 0.137071, 0.133951, 0.209588, 0.185246, 0.214665, 0.214598, 0.163624, 0.132138]})

with the following code:

fig, ax = plt.subplots()

width = 0.35

df['x'].plot(kind = 'bar',ax = ax ,width = width, position = 0 , yerr = df['x_err'],color = 'red',use_index = True)
ax.set_ylabel('X')

ax1= ax.twinx()

df['y'].plot(kind = 'bar',ax = ax1 ,width = width, position = 1 , yerr = df['y_err'],color = 'blue',use_index = True)
ax1.set_ylabel('Y')
plt.show()

and got the following plot: enter image description here

The plot is okay except for the red bar in the last group i.e. group bar 11 (shown by arrow) only appears half. I know that after reducing the width I can visualize it. The problem is the bars become thin, which I do not want. As you can see, there is still plenty of gap between two successive groups, I want to reduce the gap and accommodate all bars clearly.

Any help would be highly appreciated.

CodePudding user response:

That's due to the fact that you modify the position of the bars with position. Try adjusting xlims:

# other plotting functions
# ...

xlims = ax1.get_xlim()
ax1.set_xlim(xlims[0], xlims[1]   width)
plt.show()

Output:

enter image description here

  • Related