Save matplotlib graph in a ppt file using python-pptx without saving figure

muazfaiz picture muazfaiz · May 9, 2017 · Viewed 10.6k times · Source

Is there any way to plot the matplotlib graph in a powerpoint presentation using python-pptx without saving the graph as *.jpg or *.png ? Below is the naive way is to save the matplotlib figure as image file and then loading it to python-pptx but that is not efficient way at all.

import numpy as np
import matplotlib.pyplot as plt
from pptx import Presentation
from pptx.util import Inches 

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")
plt.plot([70, 70], [100, 250], 'k-', lw=2)
plt.plot([70, 90], [90, 200], 'k-')

plt.show()
plt.savefig('graph.jpg')
img = 'graph.jpg'
prs = Presentation()
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)
pic = slide.shapes.add_picture(img, Inches(1), Inches(1), height=Inches(1))

Answer

scanny picture scanny · May 9, 2017

The plot can be saved as an in-memory file-like object (StringIO), and then passed to python-pptx:

from StringIO import StringIO

image_stream = StringIO()
plt.savefig(image_stream)
pic = shapes.add_picture(image_stream, x, y, cx, cy)