title: Matplotlib - Stacked Bar Chart with ~1000 Bars
body: <h3>Background:</h3>
  <p>I'm working on a program to show a 2d cross section of 3d data.  The data is stored in a simple text csv file in the format x, y, z1, z2, z3, etc.  I take a start and end point and flick through the dataset (~110,000 lines) to create a line of points between these two locations, and dump them into an array.  This works fine, and fairly quickly (takes about 0.3 seconds).  To then display this line, I've been creating a matplotlib stacked bar chart.  However, the total run time of the program is about 5.5 seconds.  I've narrowed the bulk of it (3 seconds worth) down to the code below.<br />
  'values' is an array with the x, y and z values plus a leading identifier, which isn't used in this part of the code.  The first plt.bar is plotting the bar sections, and the second is used to create an arbitrary floor of -2000.  In order to generate a continuous looking section, I'm using an interval between each bar of zero.</p>
  <pre><code>    import matplotlib.pyplot as plt
  
      for values in crossSection:
          prevNum = None
          layerColour = None
          if values != None:
              for i in range(3, len(values)):
                  if values[i] != 'n':
                      num = float(values[i].strip())
                      
                      if prevNum != None:
                          plt.bar(spacing, prevNum-num, width=interval, \
                                  bottom=num, color=layerColour, \
                                  edgecolor=None, linewidth=0)
                          
                      prevNum = num
                      
                      layerColour = layerParams[i].strip()
                      
              if prevNum != None:        
                  plt.bar(spacing, prevNum+2000, width=interval, bottom=-2000, \
                                      color=layerColour, linewidth=0)
          
          spacing += interval
  </code></pre>
  <p>I'm sure there's a more efficient way to do this, but I'm new to Matplotlib and still unfamilar with its capabilities.  The other main use of time in the code is:</p>
  <pre><code>plt.savefig('output.png')
  </code></pre>
  <p>which takes about a second, but I figure this is to be expected to save the file and I can't do anything about it.</p>
  <h3>Question:</h3>
  <p>Is there a faster way of generating the same output (a stacked bar chart or something that looks like one) by using <code>plt.bar()</code> better, or a different Matplotlib function?</p>
  <p><em><strong>EDIT:</strong></em>
  I forgot to mention in the original post that I'm using Python 3.2.3 and Matplotlib 1.2.0</p>