Visualizing User Journeys Using Sankey, BigQuery, and Python

Photo by Choong Deng Xiang on Unsplash Photo by Choong Deng Xiang on Unsplash

(re-) Create custom visual flow diagrams when your analytics or data visualization platform does not provide them out of the box.

--

--

In this post, I will show how flow diagrams work, how to prepare data for that kind of diagram, and how to render the data into an impactful data visualization.

When Google released Google Analytics 4, it ruffled a few feathers in the digital analytics and marketing industries because it brought about a revolution in the way data was collected, processed and visualized.

Yes, GA4 brought a new, flat data model meant for more technically savvy audiences.

Yes, beloved features from Universal Analytics (UA) are not available yet in GA4 at the time of this Medium post.

Yes, GA4 made reporting more complicated without using custom reports in Explorations or Google Looker Studio.

One family of beloved visualizations from UA that is no longer available in GA4 is the Flow reports, which show how traffic and interactions flow from one element to another, e.g. from clickstream to pages.

Goal Flow diagram from Google Universal Analytics. Photo by author. Goal Flow diagram from Google Universal Analytics. Photo by author.

What are flow diagrams and how do they work?

Flow diagrams are visual representations of a process, an algorithm, or a sequence. They use different shapes and arrows to show the sequence of steps or actions within the process. Each shape represents a specific action, decision, or endpoint, and arrows indicate the flow of control from one step to another.

Flow diagrams help in understanding the logic and sequence of a process, making it easier to identify errors or optimize the process. When it comes to data visualization, color schemes and line thickness can be used to classify data or emphasize performance.

Sankey diagram — credit: Wikipedia Sankey diagram — credit: Wikipedia

Sankey diagrams are a form of flow diagram that show the flow of quantities from one set of values to another. Sankey diagrams use interconnected arrows to represent the flow of data, energy, or resources between different nodes. They are commonly used to visualize energy or material flows in various systems, highlighting the proportions and relationships between different components.

Sankey diagrams are powered by data elements in the form of source, target, and value (or count).

In this post, we will cover the use case of visualizing user journeys between pages of a website. To do that, we need a specific dataset that will match Sankey data visualization engines.

Preparing the data

For the purposes of this exercise, we will be using Google Analytics 4 data as stored in Google BigQuery. Assuming the data export is set up between your GA4 property and your BigQuery dataset, we can now run a query that will retrieve the page path, the page referrer, and the number of times this path/referrer pair is found in the data.

The SQL query can look a lot like the query below:

# Retrieve page path, page referrer, and path count from GA4 data
SELECT
SELECT
value.string_value FROM UNNEST (event_params)
WHERE key = ‘pagePath’
AS page_path,
SELECT value.string_value FROM UNNEST (event_params)
WHERE key = ‘page_referrer’
AND value.string_value LIKE “%yoursite.com%”
AS page_referrer,
count(*) as paths_taken
FROM

your data set goes here

`my-bq-project.analytics_12345678.events_intraday_202402*`
WHERE event_name = ‘page_view’
GROUP BY 1,2

We can refine the query to differentiate between “regular” pages and landing pages, or prefix page path with “Landing”.

With the above query, we should get a table like the following:

If your data is more explicit when it comes to sequencing/breakdown, you could instead end up with something similar to this:

Extra credit (and budget):

If you can afford the cloud processing budget, try crawling through session IDs and analyzing page paths in sequence, and then build your Sankey-compatible data model.

Creating the code

Now that we have a basic data structure, let’s see how it can be processed.

For the sake of this example, let’s use Python. We will be using a standard packages such as plotly, which contains all the libraries you need to start with.

From the code below, you will notice that you have to juggle indices for each of your sequence elements (URLs/steps) and then create a source/target matrix of index lists, with matching counts in a third list.

# Imports - nothing too spectacular here
import plotly.graph_objects as go

# List individual steps
label_list = [‘step_1’,‘step_2’,‘step_3’,‘step_4’]

# List step IDs in the order they’re used in the source CSV
source = [‘0’,‘1’,‘0’,‘2’]
target = [‘1’,‘2’,‘2’,‘3’]

# Add path counts for each step combo
count = [‘43’,‘37’,‘25’,‘18’]

# Add colors for each step
# You can use standard colors or use RGB codes
colors = [“red”,“blue”,“green”,“orange”]

# Build the diagram
fig = go.Figure(
data=[go.Sankey(
node = dict(
pad = 30,
thickness = 20,
line = dict(color = “black”, width = 0.5),
label = label_list,
color = “orange”
),
link = dict (
source = source,
target = target,
value = count,
color = colors
)
)])
# Configure the diagram
fig.update_layout(
title_text=“Basic Sankey Diagram”,
font_size=20,
font_family=“Arial”,
font_color=“black”
)

# Display the diagram
fig.show()

The resulting output should look like the diagram below:

Sample Sankey diagram built with Python and basic CSV data. Photo by Julien Coquet. Sample Sankey diagram built with Python and basic CSV data. Photo by Julien Coquet.

As you can see, this is going to take you closer to reproducing a flow chart from the good old Universal Analytics days.

In closing

This post is meant to demonstrate the potential of a technique, the way i’ve tinkered with it for personal and work projects. Of course, I’ve gone quite a bit beyond this stage so you can definitely extend and improve on this method to fit your needs so let me know via the contact form what you used it for and do post pictures of your Sankey diagrams!