Search code examples
pythonmatplotlibdocxpython-docx

Add plots directly to a document using python package docx


I am plotting some data and I want to automatically generate a report. I can save the plot and then add it to my document. However, I prefer to do it directly, without saving step. Going through the python-docx documentation I doubt it is doable by this package. Is there another way?

My code looks like this right now

from docx import Document
from docx.shared import Inches
import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)
plt.savefig('test.png')

document = Document()
document.add_heading('Report',0)
document.add_picture('test.png', width=Inches(1.25))

document.save('report.docx')

Solution

  • Use StringIO :

    This module implements a file-like class, StringIO, that reads and writes a string buffer (also known as memory files).

    from docx import Document
    from docx.shared import Inches
    import matplotlib.pyplot as plt
    import numpy as np
    from pandas.compat import StringIO
    
    memfile = StringIO()
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2*np.pi*t)
    plt.plot(t, s)
    plt.savefig(memfile)
    
    document = Document()
    document.add_heading('Report',0)
    document.add_picture(memfile, width=Inches(1.25))
    
    document.save('report.docx')
    memfile.close()
    

    Python 3 : https://docs.python.org/3/library/io.html

    Python 2 : https://docs.python.org/2/library/stringio.html

    Or use StringIO from pandas.compat