The world’s leading publication for data science, AI, and ML professionals.

Creating Charts in Google Slides with Python

A guide to easily creating elegantly formatted charts & slides using Google APIs

Impress your audience leveraging Google’s API and the gslides package

A common gap data scientists run up against is how to programmatically create simple, elegantly formatted and company-branded visualizations in a slide deck.

Leveraging Google APIs and the package gslides you can easily create charts and tables in Google Slides that will impress your audience, all with Python!

Whether you are a data scientist wanting to level up your presentations or an analyst that’s looking to automate their manual work in Slides & Sheets, this tutorial will walk you through how you can integrate gslides into your workflow.

Example scenarios we are trying to solve

Scenario 1

A data scientist performs analysis in a Jupyter notebook using a plotting package (matplotlib, plotly, ggplot2). To share their results, they copy an image from their notebook into a slide deck.

While their analysis may be excellent, non-technical stakeholders who are comfortable in Sheets & Slides have to adjust their mental model to interpret those visualizations created in python with non-standard formatting. Questions arise such as:

Can I view the underlying data in your chart?

We want to share this material out to senior stakeholders, can you format the chart according to company brand guidelines?

Scenario 2

A data analyst has to update a deck each month for monitoring purposes. They have to fetch data from the data warehouse, export the result, copy it into a Google Sheet and update the necessary charts.

This workflow is highly manual and repetitive which makes the work tedious and demotivating for an analyst.

The solution

Data flow to create charts & tables. Image by author
Data flow to create charts & tables. Image by author

To create charts in Google slides, we can pass data from pandas to the Google Slides & Sheets API using python. What do these APIs do? A large majority of the actions you can perform manually in these platforms you can replicate through creating requests and passing them to the appropriate API.

Screenshot of Google's documentation on the requests for the Slides API. Image by author
Screenshot of Google’s documentation on the requests for the Slides API. Image by author

Where this becomes complex is that there are many requests that you need to familiarize yourself with and to create those requests you typically have to write json that is hundreds of lines of long. To avoid directly working with complicated Google API requests we can use gslides, a wrapper around the Google APIs that creates and executes requests. By configuring those requests for the user, glides enables the user to manipulate Google Sheets & Slides through simple python commands as opposed to a lengthy json request.

The equivalent json request in gslides. Image by author
The equivalent json request in gslides. Image by author

An introduction to gslides

gslides is object oriented, where each class represents a object in Google Sheets or Slides.

Classes and methods in the gslides API. Image from gslides posted with permission
Classes and methods in the gslides API. Image from gslides posted with permission
  • Spreadsheet represents a google sheet
  • Frame represents a range of data within a google sheet
  • Series represents a series or multiple series in a chart
  • Chart represents a chart that will be created in google sheets then moved to google slides
  • Table represents a table that will be created in google slides
  • Presentation represents a google slides presentation.

The initialization methods get() or create() for the Spreadsheet, Frame and Presentation classes allows the user to either get existing objects or create new ones.

For more info about the package consult the documentation here.

Setup

Using gslides relies on creating a project and credentials in the Google Cloud Platform. Here are the steps you will have to follow.

  1. Create a project in the Google Cloud Platform enabling the Slides & Sheets API.
  2. Create either Service Account or OAuth 2.0 credentials. The key difference here is if you use OAuth 2.0 any command you run will run as if your personal google account is the creator & editor. If you use a Service Account, an account with the domain <project>.iam.gserviceaccount.com will be the creator & editor. More commentary around the tradeoffs of using a Service Account can be found here.
  3. Establish your credentials

For OAuth 2.0 you will run:

import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

# These scopes are read &amp; write permissions. Necessary to run gslides
SCOPES = ['https://www.googleapis.com/auth/presentations',
         'https://www.googleapis.com/auth/spreadsheets']

creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            '<PATH_TO_CREDS>', SCOPES)
        creds = flow.run_local_server()
    # Save the credentials for the next run
    with open('token.json', 'w') as token:
        token.write(creds.to_json())

For a Service Account:

from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/presentations',
         'https://www.googleapis.com/auth/spreadsheets']

credentials = service_account.Credentials.from_service_account_file(
    '<PATH_TO_CREDS>')

creds = credentials.with_scopes(SCOPES)
  1. Download gslides

pip install gslides

Basic usage

In the most basic usage, gslides passes data from a pandas dataframe to Google Sheets then uses that data in Google Sheets to create a chart or table in Sheets & Slides. See this flow below, with the full notebook here.

1. Initialize the connection to the Google APIs

import gslides
from gslides import (
    Frame,
    Presentation,
    Spreadsheet,
    Table,
    Series, Chart
)
gslides.initialize_credentials(creds) #BringYourOwnCredentials

2. Create a presentation

prs = Presentation.create(
    name = 'demo pres'
)

3. Create a spreadsheet

spr = Spreadsheet.create(
    title = 'demo spreadsheet',
    sheet_names = ['demo sheet']
)

4. Load the data to the spreadsheet

plt_df = #Pandas DataFrame with Iris data
frame = Frame.create(
    df = plt_df,
    spreadsheet_id = spr.spreadsheet_id,   
    sheet_id = sp.sheet_names['demo sheet'],
    sheet_name = 'demo sheet',
    overwrite_data = True
)

5. Create a scatterplot

sc = Series.scatter()
ch = Chart(
    data = frame.data,       #Passing the data from the frame
    x_axis_column = 'sepal length (cm)',
    series = [sc],           #Passing the series object
    title = 'Demo Chart',
    x_axis_label = 'Sepal Length',
    y_axis_label = 'Petal Width',
    legend_position = 'RIGHT_LEGEND',
)

6. Create a table

tbl = Table(
    data = plt_df.head()
)

7. Create a slide with the scatterplot & table

prs.add_slide(
    objects = [ch, tbl],
    layout = (1,2),             #1 row by 2 columns
    title = "Investigation into Fischer's Iris dataset",
    notes = "Data from 1936"
)

The result is this slide:

Output of basic usage. Image from gslides posted with permission
Output of basic usage. Image from gslides posted with permission

With the package users can:

  • Create a new presentation
  • Create a new slide with charts or tables
  • Delete a slide
  • Create a new spreadsheet
  • Add or delete a tab in a spreadsheet
  • Add data from to pandas data frame to a spreadsheet
  • Get data from a spreadsheet to a pandas DataFrame
  • Template text into a presentation similar to Jinja
  • Force update all linked charts in a presentation with refreshed underlying data

Configurability

Where gslides shines is the flexibility offered in numerous configurable parameters. Full details of that configurability can be found here, but see below for a snapshot of what is feasible.

Image by author
Image by author

To Summarize

gslides enables analysts to easily create charts & tables in Google Slides. Based on this tutorial hopefully you have a good sense of what’s possible with gslides and how it can be implemented into your workflow. Be sure to check out the documentation here for any questions you may have.


Related Articles