Creating Presentations with Python | by Eser Saygın | Towards Data Science

Time is the most precious treasure Data Scientists have and it must be used efficiently. If you frequently prepare a presentation then it means you are consuming your time with busywork. But why should you do something like grunt work if you can automate it?
This is my second article about the automation of time-consuming works. You can find the other one that is about creating a pdf file with python by clicking here.
This article consists of five parts.
1- Getting Started
2- Adding Images
3- Adding Charts
4- Implementation
Now I’ll show you the basics of creating PowerPoint slides with Python.
python-pptx is a Python library for creating and updating PowerPoint files. This article is going to be a basic introduction to this package. If you want to learn much more about it, this is the official documentation page that you should check. Now let’s install the package if you don’t have.
pip install python-pptx
I suggest you use the pip install code line because this package depends on Ixml, Pillow and XlsxWriter packages. If you use setup.py installation method you will need to install these dependencies yourself.
It is always easy to explain something with examples. For this purpose, I am going to use official examples in the first place. At the end of the article, I am going to build a basic PowerPoint presentation page by page. Let’s start with the adding slide. To do this first we need to import the pptx package.
from pptx import Presentation
We are going to use Presentation() to open or create a presentation. Let’s assign it to a variable.
prs=Presentation()
Now we are ready to build our first slide. This slide will contain a title and a subtitle.
lyt=prs.slide_layouts[0] # choosing a slide layoutslide=prs.slides.add_slide(lyt) # adding a slidetitle=slide.shapes.title # assigning a titlesubtitle=slide.placeholders[1] # placeholder for subtitletitle.text="Hey,This is a Slide! How exciting!" # titlesubtitle.text="Really?" # subtitleprs.save("slide1.pptx") # saving file
Ok, we’ve just created our first slide. Let’s explain this code block row by row. You can think slide layouts like a template. There are nine slide layouts and we‘ve used the first one for this example. prs.slide_layouts[0] This means ‘ I am going to use a title layout’. So how do we know which one should we choose? This is all about Slide Master in PowerPoint. As you see below, the first item on slide master is “Title Slide Layout”. This is why slide_layouts[0] gives us the title object. By the way, you can use a blank layout instead of the title layout.
Secondly, we’ve used the add_slide function to add a new slide that inherits the layout. slide=prs.slides.add_slide(lyt) By doing this assignment, we’ve just added a slide layout that contains a title object (a big one!).
After this step, we’ve created a title variable. title=slide.shapes.title
Next row is subtitle=slide.placeholders[1] . This means if you want to add a subtitle then you have to add a placeholder. With .text attribute, we can assign a string on a shape.
The last step of our code block is exporting the pptx file. prs.save(“slide1.pptx”) saves the slides as pptx in our path. So here is the result;
OK, we’ve just learned how to add a slide, a title and a subtitle. Now it is time to add a chart and an image.
Before adding new elements I should mention something important. Length classes. pptx package has a util module that contains utility function and classes like Lenght, Inches etc.
from pptx.util import Inches
Here you can find source code for pptx.util. You might think, “why it is so important?”. First of all, as you know, there are two default slide sizes. Standard and Widescreen.
If you want to use a widescreen presentation, you should define slide sizes in the beginning.
prs.slide_width = Inches(16)prs.slide_height = Inches(9)
Besides that, as you will see below, we need to adjust objects to our working space. Okay, let’s keep going. Now we need to define an image path to use it later.
img_path = '/your-img-path/{your-image}.png'
Okay, halfway through. In our first example, we’ve used slide_layout[0]. This time we are going to pick the sixth layout which is blank.
prs = Presentation()blank_slide_layout = prs.slide_layouts[6]slide = prs.slides.add_slide(blank_slide_layout)
Well, we got everything we need. Let’s add an image.
path='stick2.png' prs = Presentation()blank_slide_layout = prs.slide_layouts[6]slide = prs.slides.add_slide(blank_slide_layout)
We are going to define two variables now. These variables allow you to adjust the position or move if you need to.
left=Inches(1)top=Inches(0.5)
If you check the values you will see 914400. This is EMU and there are 914400 EMUs per inch. (1 inch = 914400 EMU)
Okay, we are ready to add an image.
img=slide.shapes.add_picture(path,left,top)
pptx package supports adding or modifying charts. To do this we will use pptx.chart.data and pptx.enum.chart.
First we need to define chart data.
chart_data=ChartData()
Let’s add some categories and series.
chart_data.categories = ['Column 1', 'Column 2', 'Column 3']chart_data.add_series('Hey',    (10.5, 5.5, 17.5))chart_data.add_series('there',    (25.5, 40.3, 30.7))chart_data.add_series('reader', (5.2, 10.3, 8.4))
Now we need to define some measures. (left, top, width, height)
x,y,cx,cy=Inches(1),Inches(2),Inches(5),Inches(7)
We are now ready to add a chart.
chart=slide.shape.add_chart(XL_CHART_TYPE.LINE_MARKERS_STACKED,x,y,cx,cy,chart_data).chartprs.save('chart-02.pptx')
That’s enough for the beginning. Let’s build an end to end PowerPoint presentation.
Ok, we are white-collar and our manager wants a fast presentation for tomorrow. Yes, you can build a presentation one by one if you want.
Let’s build an automated presentation program.
Page 1:
First things first, let’s import requisite packages.
from pptx import Presentationfrom pptx.enum.shapes import MSO_SHAPEfrom pptx.dml.color import RGBColorfrom pptx.util import Inches, Ptfrom pptx.enum.dml import MSO_THEME_COLORtitle='Automated Presentation Creating Process\n\How to Create PowerPoint Presentations with Python 'pylogo='pylogo.png'pptlogo='pptlogo.png'prs = Presentation()
After importing packages I’ve defined some variables. (Title and logos). Now we can create our first page. I am going to use a widescreen layout.
slide = prs.slides.add_slide(prs.slide_layouts[6])prs.slide_width = Inches(16)prs.slide_height = Inches(9)shape = slide.shapes.add_shape(    MSO_SHAPE.RECTANGLE, 0, Inches(9/1.5),Inches(16),Inches(9/8.5))shape.shadow.inherit = Falsefill=shape.fillfill.solid()fill.fore_color.rgb=RGBColor(255,0,0)shape.text= titleline=shape.lineline.color.rgb=RGBColor(255,0,0)logo1=slide.shapes.add_picture(pylogo,Inches(13.8),Inches(6.0),height=Inches(1.0),width=Inches(1.0))logo2=slide.shapes.add_picture(pptlogo,Inches(14.5),Inches(5.8),height=Inches(1.5),width=Inches(1.5))
I’ve just added a rectangle and two images. slide.shapes.add_shape({type of shape},{left spacing},{top spacing},{width},{height}).
I’ve used shape.shadow.inherit = False to remove the shadow effect. A shape object also has a .fill property. It is the colour of the shape. The .line is a border around a shape that can have a different colour. Thus, I assigned same RGB codes for both of them. Here is the result:
Page 2:
Let’s add a chart.
slide = prs.slides.add_slide(prs.slide_layouts[6])shape = slide.shapes.add_shape(    MSO_SHAPE.RECTANGLE, 0, Inches(0.5),Inches(16),Inches(0.3))shape.shadow.inherit = Falsefill=shape.fillfill.solid()fill.fore_color.rgb=RGBColor(255,0,0)shape.text= "How to Add a Chart"line=shape.lineline.color.rgb=RGBColor(255,0,0)logo1=slide.shapes.add_picture(pylogo,Inches(14.5),Inches(0.4),height=Inches(0.5),width=Inches(0.5))logo2=slide.shapes.add_picture(pptlogo,Inches(15.0),Inches(0.4),height=Inches(0.5),width=Inches(0.5))from pptx.chart.data import CategoryChartDatafrom pptx.enum.chart import XL_CHART_TYPEfrom pptx.chart.data import ChartDataimport numpy as np import datetimeN = 100random_x = np.random.randn(N) + 10random_y = np.random.randn(N)+5random_z = np.random.randn(N) +20dte=datetime.datetime.today()dt_lst=[dte-datetime.timedelta(days=i) for i in range(N)]chart_data = ChartData()chart_data.categories = dt_lstchart_data.add_series('Data 1',    random_x)chart_data.add_series('Data 2',    random_y)chart_data.add_series('Data 3',    random_z)x, y, cx, cy = Inches(1), Inches(2), Inches(14), Inches(6)chart = slide.shapes.add_chart(    XL_CHART_TYPE.LINE, x, y, cx, cy, chart_data).chartchart.has_legend = Truechart.legend.include_in_layout = Falsechart.series[2].smooth = True
I’ve just added a line chart with random variables on a blank slide. You can find chart types here.
slide.shapes.add_chart({type of chart},{left spacing},{top spacing},{width},{height}, {chart data}).
Page 3:
If you want you can add a plotly chart as an image. Let’s see how to do that.
slide = prs.slides.add_slide(prs.slide_layouts[6])shape = slide.shapes.add_shape(    MSO_SHAPE.RECTANGLE, 0, Inches(0.5),Inches(16),Inches(0.3))shape.shadow.inherit = Falsefill=shape.fillfill.solid()fill.fore_color.rgb=RGBColor(255,0,0)shape.text= "How to Add an Image"line=shape.lineline.color.rgb=RGBColor(255,0,0)logo1=slide.shapes.add_picture(pylogo,Inches(14.5),Inches(0.4),height=Inches(0.5),width=Inches(0.5))logo2=slide.shapes.add_picture(pptlogo,Inches(15.0),Inches(0.4),height=Inches(0.5),width=Inches(0.5))import plotly.graph_objects as goimport pandas as pddf = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/718417069ead87650b90472464c7565dc8c2cb1c/sunburst-coffee-flavors-complete.csv')fig = go.Figure(go.Sunburst(        ids = df.ids,        labels = df.labels,        parents = df.parents))fig.update_layout(uniformtext=dict(minsize=10, mode='hide'))fig.write_image("img.png")imgpth='img.png'left = top = Inches(1)pic = slide.shapes.add_picture(imgpth, left, top)
We’ve used a Plotly sunburst example.
slide.shapes.add_picture({image path},{left spacing},{top spacing}).
Page 4:
Finally, let’s add a text box.
slide = prs.slides.add_slide(prs.slide_layouts[6])shape = slide.shapes.add_shape(    MSO_SHAPE.RECTANGLE, 0, Inches(0.5),Inches(16),Inches(0.3))shape.shadow.inherit = Falsefill=shape.fillfill.solid()fill.fore_color.rgb=RGBColor(255,0,0)shape.text= "How to Add an Image"line=shape.lineline.color.rgb=RGBColor(255,0,0)logo1=slide.shapes.add_picture(pylogo,Inches(14.5),Inches(0.4),height=Inches(0.5),width=Inches(0.5))logo2=slide.shapes.add_picture(pptlogo,Inches(15.0),Inches(0.4),height=Inches(0.5),width=Inches(0.5))left = Inches(1)top = Inches(2)width = Inches(12)height = Inches(5)text_box=slide.shapes.add_textbox(left, top, width, height)tb=text_box.text_frametb.text='Do you know how the Orcs first came into being? They were elves once,\n\taken by the dark powers, tortured and mutilated. A ruined and terrible form of life.\n\Now... perfected. My fighting Uruk-Hai. Whom do you serve?'prg=tb.add_paragraph()prg.text=" "prg=tb.add_paragraph()prg.text="They will find the Ring, and kill the one who carries it."
There are two different text code blocks. First one is about textbox. slide.shapes.add_textbox(left, top, width, height) With tb.text you can add text inside the textbox. If you want to add another paragraph then you should use tb.add_paragraph().
Here is the result:
Page 5:
And finally, we’ve finished our basic presentation. Maybe you just want to add a thank you page :)
slide = prs.slides.add_slide(prs.slide_layouts[6])shape = slide.shapes.add_shape(    MSO_SHAPE.RECTANGLE, 0, Inches(4.0),Inches(16),Inches(1.0))shape.shadow.inherit = Falsefill=shape.fillfill.solid()fill.fore_color.rgb=RGBColor(255,0,0)shape.text= "Thank You"line=shape.lineline.color.rgb=RGBColor(255,0,0)logo1=slide.shapes.add_picture(pylogo,Inches(14.5),Inches(4.0),height=Inches(1.0),width=Inches(1.0))logo2=slide.shapes.add_picture(pptlogo,Inches(15.0),Inches(4.0),height=Inches(1.0),width=Inches(1.0))
And do not forget to save :)
prs.save('basic_presentation.pptx')
Conclusion
As I said at the very beginning of this article designing a presentation is a time-consuming process. As a goblin said, “time is money, friend!”.
This is the basic example of creating a PowerPoint presentation with Python. You can define functions and run them when you need. For further information visit the pptx document page.
Thanks for reading!