Home > OS >  Matplotlib - why is only the last bar adjusting width in each part?
Matplotlib - why is only the last bar adjusting width in each part?

Time:04-27

I am having trouble understanding why when I change the width from 0.2 to 0.5, only the far right series (group_c) changes. has anyone run into this?

Picture included for reference of graph output.

  • a - o are just rand ints
group_a = (a,b,c,d,e)
group_b = (f,g,h,i,j)
group_c = (k,l,m,n,o)
width = 0.5
x = np.arange(5)

#I think it is something in here, but not sure what
plt.bar(x-0.2, group_a, width, color = 'cyan')
plt.bar(x, group_b, width, color = 'orange')
plt.bar(x 0.2, group_c, width, color = 'green')

plt.xticks(x, ['1','2','3','4','5'])
plt.xlabel("quarter")
plt.ylabel('%')
plt.legend(['Group A','Group B','Group C'])
plt.show()

[picture of output]

1

CodePudding user response:

I am guessing that the width is correct, but the bars are just behind each other. Perhaps, by adding some transparency with alpha you can see it clearly.

group_a = (a,b,c,d,e)
group_b = (f,g,h,i,j)
group_c = (k,l,m,n,o)
width = 0.5
x = np.arange(5)
plt.bar(x-0.2, group_a, width, color = 'cyan')
plt.bar(x, group_b, width, alpha = .5, color = 'orange')
plt.bar(x 0.2, group_c, width, alpha = .1, color = 'green')
plt.xticks(x, ['1','2','3','4','5'])
plt.xlabel("quarter")
plt.ylabel('%')
plt.legend(['Group A','Group B','Group C'])
plt.show()

CodePudding user response:

The bars are just overlapping because the offset is less than the widths of the bars. By changing the order you add them to the plot you can see that the overlap differently.

import matplotlib.pyplot as plt
import numpy as np

group_a = 5*[20]
group_b = 5*[40]
group_c = 5*[100]
width = 0.5
x = np.arange(5)

#I think it is something in here, but not sure what
plt.bar(x-0.2, group_a, width, color = 'cyan')
plt.bar(x 0.2, group_c, width, color = 'green')
plt.bar(x, group_b, width, color = 'orange')

plt.xticks(x, ['1','2','3','4','5'])
plt.xlabel("quarter")
plt.ylabel('%')
plt.legend(['Group A','Group B','Group C'])
plt.show()

enter image description here

  • Related