title: Writing pandas/matplotlib image directly into XLSX file
body: <p>I am generating plots in pandas/matplotlib and wish to write them to an XLSX file. I am not looking to create native Excel charts; I am merely writing the plots as non-interactive images. I am using the <a href="https://xlsxwriter.readthedocs.org/" rel="noreferrer">XlsxWriter library/engine</a>.</p>
  
  <p>The closest solution I have found is <a href="https://stackoverflow.com/questions/24907210/insert-pandas-chart-into-an-excel-file-using-xlsxwriter">the answer to this SO question</a>, which suggests using the <a href="http://xlsxwriter.readthedocs.org/worksheet.html#worksheet-insert-image" rel="noreferrer">XlsxWriter.write_image()</a> method. However, this method appears to take a filename as its input. I am trying to programmatically pass the direct output from a pandas/matplotlib <code>plot()</code> call, e.g. something like this:</p>
  
  <pre><code>h = results.resid.hist()
  worksheet.insert_image(row, 0, h) # doesn't work
  </code></pre>
  
  <p>or this:</p>
  
  <pre><code>s = df.plot(kind="scatter", x="some_x_variable", y="resid")
  worksheet.insert_image(row, 0, s) # doesn't work
  </code></pre>
  
  <p>Is there any way to accomplish this, short of the workaround of writing the image to a disk file first?</p>
  
  <h1>Update</h1>
  
  <p>Answer below got me on the right track and am accepting. I needed to make a few changes, mainly (I think) because I am using Python 3 and perhaps some API changes. Here is the solution:</p>
  
  <pre><code>from io import BytesIO
  import matplotlib.pyplot as plt
  
  imgdata = BytesIO()
  fig, ax = plt.subplots()
  results.resid.hist(ax=ax)
  fig.savefig(imgdata, format="png")
  imgdata.seek(0)
  
  worksheet.insert_image(
      row, 0, "",
      {'image_data': imgdata}
  )
  </code></pre>
  
  <p>The <code>""</code> in the <code>insert_image()</code> code is to trick Excel, which is still expecting a filename/URL/etc.</p>