5

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))
muazfaiz
  • 4,611
  • 14
  • 50
  • 88

1 Answers1

8

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

import io

image_stream = io.BytesIO()
plt.savefig(image_stream)
pic = shapes.add_picture(image_stream, x, y, cx, cy)
scanny
  • 26,423
  • 5
  • 54
  • 80
  • So here we are saving it too. with `plt.savefig(image_stream)`. Can we do it without saving ? – muazfaiz May 10 '17 at 07:34
  • 2
    Yes, but that would involve digging into the internals of `python-pptx` and bypassing the API. Just what are you trying to achieve? I thought you wanted to avoid disk access. If you're trying to save the memory read/write I'd have to say It sounds to me like [premature optimization](http://wiki.c2.com/?PrematureOptimization). – scanny May 10 '17 at 07:51
  • StringIO didn't work for me--I think BytesIO() should be used now. – robbwh Dec 12 '21 at 22:05
  • 1
    Good catch @robbwh, I've updated the code to Python 3 :) – scanny Dec 14 '21 at 05:04