title: Dynamically serving a matplotlib image to the web using python
body: <p>This question has been asked in a similar way <a href="https://stackoverflow.com/questions/5515278/plot-matplotlib-on-the-web">here</a> but the answer was way over my head (I'm super new to python and web development) so I'm hoping there's a simpler way or it could be explained differently.</p>
  
  <p>I'm trying to generate an image using matplotlib and serve it without first writing a file to the server. My code is probably kind of silly, but it goes like this:</p>
  
  <pre><code>import cgi
  import matplotlib.pyplot as pyplot
  import cStringIO #I think I will need this but not sure how to use
  
  ...a bunch of matplotlib stuff happens....
  pyplot.savefig('test.png')
  
  print "Content-type: text/html\n"
  print """&lt;html&gt;&lt;body&gt;
  ...a bunch of text and html here...
  &lt;img src="test.png"&gt;&lt;/img&gt;
  ...more text and html...
  &lt;/body&gt;&lt;/html&gt;
  """
  </code></pre>
  
  <p>I think that instead of doing pyplot.savefig('test.png'), I am supposed to create a cstringIO object and then do something like this: </p>
  
  <pre><code>mybuffer=cStringIO.StringIO()
  pyplot.savefig(mybuffer, format="png")
  </code></pre>
  
  <p>But I am pretty lost from there. All the examples I've seen (e.g. <a href="http://lost-theory.org/python/dynamicimg.html" rel="noreferrer">http://lost-theory.org/python/dynamicimg.html</a>) involve doing something like </p>
  
  <pre><code>print "Content-type: image/png\n"
  </code></pre>
  
  <p>and I don't get how to integrate that with the HTML I'm already outputting. </p>