Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 917
Laleh Avatar asked Jun 05 '26 00:06

Laleh


1 Answers

Try the code below in python 3 to directly save the plot in document.

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

memfile = BytesIO()
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()
like image 149
Lolo Buys Avatar answered Jun 07 '26 15:06

Lolo Buys



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!