Jupyter Notebooks in WordPress

Jupyter Notebooks in WordPress

While it might look like a normal WordPress blog post (like all the previous posts on our blog), you are actually looking at a Jupyter Notebook.

If you are not familiar with Jupyter Notebooks then here’s what you need to know about them:

The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include: data cleaning and transformation, numerical simulation, statistical modelling, data visualization, machine learning, and much more.

In this first proof-of-concept blog post/Notebook, we are showing you how Notebooks work and a few cool things you can accomplish with them.

Why are we doing this?

The reason we are testing with “blogging using a Jupyter Notebook” is that it allows us to share our code example and analysis done in Python more easily and in a more repeatable way.

At Reflective Data, we are using a lot of Python in all steps of data analysis. Jupyter Notebooks is a tool we use to run and share our code both internally and with our clients. Why not leverage the same workflow in our blogging efforts as well, we thought.

Our plan is to create a series of useful tutorial-type blog posts where we show you how to use Python (and Notebooks) in your everyday work as a digital analyst. We are going to pull data from Google Analytics, testing tools and databases, then run all sorts of analysis and visualizations using this data (and Notebooks).

How are we doing this?

Since sharing Notebooks is all about repeatability, we thought it will be wise to also share how we managed to turn Notebooks into a WordPress blog post.

While you can host and run Jupyter Notebooks both locally or on the cloud, we’ve found Colaboratory by Google to be the best solution when it comes to (as the name suggests) collaborative coding. That’s why we are mostly using Colab when working with Notebooks.

Turning a Notebook into HTML

The first step in the process of sharing your Notebook on WordPress would be turning your Notebook from ipynb format into HTML.

The hosted version of Jupyter Notebooks comes with a handy “Download as HTML” option built-in. Colab, unfortunately, doesn’t have this feature. So, we found a workaround which also allowed us to semi-automate the whole process.

We are using Google Drive’s API to load the ipynb file from Drive (Colab hosts Notebooks on your Drive) and then using nbpreview to turn it to HTML. We haven’t yet done so, but the plan is to build a WordPress plugin that would take a Colab Notebook’s ID and then automatically turn it into HTML.

Teaching WordPress how to render a Notebook

Currently, we simply paste the HTML version of the Notebook into WordPress blog post using a text-edit-mode. This will soon be handled by the plugin we mentioned in the previous step.

Everey blog post that contains a Notebook will receive a tag “notebook”. Using this tag we can then tell WordPress to load some extra CSS to properly render the Notebook.

We are currently doing this in a few lines of code in our functions.php file.

add_action('wp_head', 'load_notebook_styles');
function load_notebook_styles() {
    if ( has_tag( 'notebook' ) ) {
        wp_enqueue_style( 'notebook-css', get_template_directory_uri() . '/notebooks/notebook.css' );
        wp_enqueue_style( 'notebook-prism-css', get_template_directory_uri() . '/notebooks/prism.css' );
    }
}

Here are the CSS files we load:

What’s possible with Notebooks?

So, now that you have at least a basic knowledge of what a Notebook is and how we managed to turn them into WordPress blog posts, let’s see what you could actually accomplish with them.

Them main thing, of course, is that you can run Python code and immediately see the output.

Here’s a very basic example:

x = 5
for i in range(x):
  print(i * '*')
*
**
***
****

Awesome, right?

Now, the only limits you really have are your creativity and Python skills. In the upcoming blog posts, our goal is to get you better at both by showing some cool and useful things we are doing using Python and Jupyter Notebooks.

While the first Python script was quite useless, let’s try and load in some real data from Google Analytics.

First, let’s import our required dependencies.

import pandas as pd
import json
import requests

There are many ways you can pull data from Google Analytics but one of the simplest is by using the API Query URI that you can grab from the Query Explorer.

In this example, we are loading the number of Sessions and Users per day for the last 30 days.

from getpass import getpass # required only for hiding your variables
api_query_uri = getpass('Enter API Query URI here') # get the URI
r = requests.get(api_query_uri) # make the request
data= r.json() # read data from a JSON format
df = pd.DataFrame(data['rows']) # turn data into a Pandas data frame
df = df.rename(columns={0: 'Date', 1: 'Sessions', 2: 'Users'}) # giving the columns some proper titles
df['Sessions'] = df['Sessions'].astype(int) # formatting sessions as ints
df['Users'] = df['Users'].astype(int) # formatting users as ints
df['Date'] = pd.to_datetime(df['Date'])
df.head() # printing the first five rows
Enter API Query URI here··········
Date Sessions Users
0 2019-09-12 50526 58667
1 2019-09-13 53919 63156
2 2019-09-14 58735 68200
3 2019-09-15 67371 77597
4 2019-09-16 65780 77305

Great, so our data is now loaded and formatted for our needs.

Let’s go ahead and try visualizing it. For timeseries data, a line chart should work well.

df.plot.line(x='Date', y=['Sessions', 'Users'], ylim=[0,None], figsize=[10, 6])
<matplotlib.axes._subplots.AxesSubplot at 0x7fc6a53c3278>

That was simple, right?

There is so much more you can do with Python and Jupyter Notebooks and we are going to cover more advanced stuff in our upcoming blog posts.

I’d like to end this post with a few thoughts I got while writing this one.

  1. Writing a blog post using Markdown is fun (and effective). I know some people are doing it but this is the first time for me. Markdown is the way you write text in Notebooks.
  2. While I thought so before, now I know for sure that Notebooks + WordPress is a really good solution for sharing Python code examples and data visualizations online.
  3. I’d love to hear your thoughts, ideas, questions and topic suggestions in the comments below! We are happy to respond/help.

PS! More Notebooks-related content is coming soon! Consider subscribing to our newsletter.

2 thoughts on “Jupyter Notebooks in WordPress

  1. Are you sure there doesn’t already exist a plugin that solves this? I haven’t checked myself but would think there is one.

    1. We’ve checked but never found one. Should someone know about a plugin that makes embedding Jupyter Notebooks in WordPress easy, please let us know!

Leave a Reply

Your email address will not be published. Required fields are marked *

Sign up for Reflective Data

5,000 sessions / month ×

Please enter your email

Submit

After submitting your email, we will send you the registration form.