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')
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With