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 = """
        trains, ideal, correct, deficient, without
        FROM __matplotlib.rabat
# execute the query

# retrieve the whole result set
data = cur.fetchall()

# 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.title('Qualite du rabattement par depart de train')
plt.xticks(ind+width/2., trains)


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: Database

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 : Real results

Those are ok, but where made in Excel after a VERY tedious process than I'm trying to automate with a python script...

  • Not fair! ;) It is about GIS. It's only a small part of a script that loads GTFS data into PostGIS, analyse them, do some statistical analysis about the quality of the fedding bus system, and then batch map the results in ArcGIS with arcpy.mapping. I just didn't want to bother you with all the context, only some that is relevant to my question. That part is not 100% GIS, but my global problem is... – fgcartographix Sep 20 '12 at 19:13
  • 1
    This would probably get more attention on SO. – Chad Cooper Sep 20 '12 at 19:43
  • 2
    I apologies for necroing a closed question, but I came after looking everywhere else for an answer to the same question. Using the example above I finally figured out the problem comes from the bottom parameter acting as an offset, and therefore must be cumulative. To give the bars the right offset we therefore need to add the bottom values together as we progress: bottom=ideal+correct and bottom=ideal+correct+deficient – CSkau May 20 '13 at 8:43
  • Why closing instead of migrating? – Franck Dernoncourt Oct 31 '15 at 0:42

Browse other questions tagged or ask your own question.