0

I am trying to create stack bar chart using matplotlib using following code but the starting and ending point of second part is wrong

import numpy as np
import matplotlib.pyplot as plt

N = 7
m = (5,10,30,40,0,0,0)      #(0-5,0-10,26-30,36-40)
w = (15,25,35,0,0,0,0)      #(11-15,16-25,31-35)
ind=[5,10 ,15 ,25 ,30,35,40] 
# the x locations for the groups
width = 0.55       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, m, width, color='r')
p2 = plt.bar(ind, w, width, color='y',bottom=m)

plt.show()

but #(0-5,0-10,26-30,36-40) #(11-15,16-25,31-35) bar chart plot on each other but i want first part would be 0 to 5 and second part will be 6 to 15 but it gives 5+15=20 that is wrong i don't want to join it. i mean if first part is 0-5 and second part is 6-15 so that it will show 0-5 and 6-15 not up to 5+15 = 20

tmdavison
  • 64,360
  • 12
  • 187
  • 165
sohamkumar
  • 33
  • 7

1 Answers1

0

So if I understand you correctly, you don't really want a stacked bar chart, you want w to plot behind m. You can do this by setting the zorder of m to be lower than w:

p1 = plt.bar(ind, m, width, color='r',zorder=2)
p2 = plt.bar(ind, w, width, color='y',zorder=1)

enter image description here

Alternatively, if you want to keep the bottom=m option, you need to subtract m from w. First, you need to convert m and w to numpy.array. Then you could plot p2 like this:

p2 = plt.bar(ind, np.maximum(w-m,0), width, color='y',bottom=m)

Note that you have to use np.maximum to prevent w going negative, for example when m=40 and w=0.

tmdavison
  • 64,360
  • 12
  • 187
  • 165
  • thanks this right I have one more question I have some range for example 0-5 normal 6-10 normal 11-25 i trapping and again 26-35 normal how could i display this range an label on single bar with different colour but same category should have the same colour – sohamkumar Oct 13 '15 at 11:49
  • I want this value on single bar not 2-3 bar with different colour and same category should be having same colour – sohamkumar Oct 13 '15 at 12:24