I'm trying to create a stacked bar chart in python with matplotlib and I can draw my bar one up the other
# -*- coding: utf-8 -*- import psycopg2 import matplotlib.pyplot as plt import numpy as np # Connect to an existing database conn = psycopg2.connect("dbname=RABATTEMENT user=postgres password=#######") # Open a cursor to perform database operations cur = conn.cursor() # this is the query we'll be making query = """ SELECT trains, ideal, correct, deficient, without FROM __matplotlib.rabat """ # execute the query cur.execute(query) # retrieve the whole result set data = cur.fetchall() cur.close() conn.close() # unpack data trains, ideal, correct, deficient, without = zip(*data) N = len(trains) #-- Number of trains ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars: can also be len(x) sequence p1 = plt.bar(ind, ideal, width, color='green') p2 = plt.bar(ind, correct, width, color='yellow', bottom=ideal) p3 = plt.bar(ind, deficient, width, color='red', bottom=correct) p4 = plt.bar(ind, without, width, color="grey", bottom=deficient) plt.ylabel('%') plt.title('Qualite du rabattement par depart de train') plt.xticks(ind+width/2., trains) plt.yticks(np.arange(0,100,25)) plt.show()
My problem is that the documentation only show how to stack 2 bars. So, you have p1 (ideal) and p2 (correct) where bottom=ideal.
If I want to add a 3rd bar, I thought that putting for p3 bottom=correct (p2), that you draw it correctly, but the 3rd bar is drawn behind the first 2, and it's bottom value is p2.
My original data (fields are in French, but I translated them in the right order:
I tried using int() or..., but since my variables are lists.
What I'm trying to achieve is a 100% total each time as in :
Those are ok, but where made in Excel after a VERY tedious process than I'm trying to automate with a python script...