Search code examples
pythonmatplotlib

adding matplotlib plot directly to word document without saving image to disk first


I can add a plot generated by matpltlib to word file (using python-docx) if I save the plot as a .png file first using the following lines of code

plt.savefig(path_to_file)

doc.add_picture(path_to_file, width=Inches(3))

Is there a way I can just add the plot directlty to the word document without saving as an image first. Using

doc.add_picture(plt, width=Inches(3))

produces a module 'matplotlib.pyplot' has no attribute 'seek' error


Solution

  • The python-docx function add_picture takes a path or a stream as first argument, and matplotlib can return a figure as a buffer, so presumably the following should work:

    import matplotlib.pyplot as plt
    
    from io import BytesIO
    
    fig, ax = plt.subplots()
    ... 
    
    # render the figure
    fig.canvas.draw()
    
    # save to buffer
    buffer = BytesIO()
    fig.savefig(buffer, format="png")
    
    # hand buffer to python-docx
    doc.add_picture(buffer)