Looping and Naming Variables in Python Bar Chart
Question: I'm using matplotlib in Python to create a stacked bar chart showing order
volume over the course of the day by hour, versus a calendar equivalent day
last year.

I've already arranged an array that includes today's and last year's order
volume:

    
    
    allorders=[(23, 28), (15, 7), (15, 5), (8, 9), (4, 2), (5, 3), (4, 6), (8, 10), (28, 24), (45, 46), (55, 65), (0, 74), (0, 64), (0, 58), (0, 62), (0, 62), (0, 42), (0, 43), (0, 38), (0, 39), (0, 32), (0, 40), (0, 41), (0, 16)]
    

For stacked bars, you would normally use the following syntax:

    
    
    import matplotlib.pyplot as plt
    import numpy as np
    n=2
    ind = np.arange(n) 
    width = 0.35       
    plt.ylabel('Orders')
    plt.xticks(ind+width/2., ('Today', 'Last Year on Calendar Equivalent'))
    plt.yticks(np.arange(0,plottotal,10))
    
    p1= plt.bar(ind, allorders[0],   width, color='#000099')
    p2= plt.bar(ind, allorders[1],   width, color='#000099', bottom=allorders[0])
    

however, this can be daunting with large amount of stacked charts. Therefore,
I'm trying to create a loop to go through the 'allorders' array and stack them
via:

    
    
     for i in allorders:
         if i=0:
           p1=plt.bar(ind, allorders[i],   width, color='#000099')
           bottomcounter=allorders[i]
    
         else: 
           'p+i' = plt.bar(ind, allorders[i],   width, color='r', bottom=bottomcounter)
           bottomcounter=bottomcounter+allorders[i]
    

but, I get all sorts of errors, including that the clause 'if i=0' has invalid
syntax, and that 'p+i'cannot be used to auto-name variables.

So, SO wizards:

1) how do you name new variables automatically in a loop (so when i=0, the
variable is named p0, when i=1, the variable is named p1, etc.)

2) what's wrong with including the 'if i=0' clause?

Since I'm new to Python (coming from R and Stata), please treat me like an
infant, with step-by-step code if you can!

Thanks!


Answer: To start with, you need to read and understand the official
[tutorial](http://docs.python.org/2/tutorial/).

Second, to fix your code:

    
    
    import itertools
    allorders=[(23, 28), (15, 7), (15, 5), (8, 9), (4, 2), (5, 3), (4, 6), (8, 10), (28, 24), (45, 46), (55, 65), (0, 74), (0, 64), (0, 58), (0, 62), (0, 62), (0, 42), (0, 43), (0, 38), (0, 39), (0, 32), (0, 40), (0, 41), (0, 16)]
    width = .35
    plts = []
    colors = ['k','r','b']
    
    for i,order in enumerate(allorders):
        bottom_counter = 0
        loc_plts = []
        for o,c in zip(order,itertools.cycle(colors)):
            tmp_plt = plt.bar(i, o, width, color=c, bottom=bottom_counter)
            loc_plts.append(tmp_plt)
            bottom_counter+=o
        plts.append(loc_plts)
    

