Plotly Subplots & Plot Layering
Tags: Subplot, Data, Dataviz, Python, Plotly

Hi everyone, in this story we will try to cover subplots and plot layering in Plotly. Before we start firstly I need to explain my situation. I’m trying to learn English so please don’t judge me for my English 😅 Let’s try to cover subplots and plot layering.

What are The Subplots

We can say, mini plots which arranged in the grid. We

can show different plots which from the same dataset

can show the same plots of different subsets of a dataset

How Can Use Subplots

We need to import make_subplots from under plotly.subplots. Please don’t forget, at the time this article was written, make_subplots not supporting plotly.express. So we can not use make_subplots with plotly.express plots.

We’ll use this code for importing the library to project.

from plotly.subplots import make_subplots

During this article we’ll use these libraries and we’ll use tips dataset from under seaborn.

import pandas as pd # creating and manipulating dataframes

import seaborn as sns # accessing to dataset

import plotly.graph_objects as go # we can not use express plots

from plotly.subplots import make_subplots # creating subplots

Let’s Create the First Subplot

I’ll create bar plot. Because of that I’m grouping the data.

df = sns.load_dataset('tips')

grouped_df = df.groupby(['sex', 'day'], as_index=False).sum()

grouped_df.head()

And now I need to create parsed grid. In this example I’ll create 1x2 (column x row) grid. I’m doing it with using make_subplots function.

fig = make_subplots(rows=1, cols=2)

After that It’ll return me a Figure object. We know it from Plotly. And we are going to add our plots on the that figure object with using add_trace function. Please don’t forget, we need to give specific column and row number which our created graph will come.

# add the 1st graph by specifying which row and column it will come to

fig.add_trace(go.Bar(x=grouped_df[grouped_df['sex'] == 'Male']['day'], y=grouped_df[grouped_df['sex'] == 'Male']['tip'], name='Male'),row=1, col=1) # add the 2nd graph

fig.add_trace(go.Bar(x=grouped_df[grouped_df['sex'] == 'Female']['day'], y=grouped_df[grouped_df['sex'] == 'Female']['tip'], name='Female'), row=1, col=2)

after execute code which we coded, we’ll see this plot

Let’s Make Some Makeup to Our Plots

Set Title to each Subplot

In this section we’ll set the titles for each subplot. We need to use subplot_titles parameter in make_subplots function. This parameter takes one list which contains subplot titles. Please don’t forget, titles must be queue in this list. 0 index will be 1st’s graph’s title.

I’ll use same traces and dataset.

grouped_df = df.groupby(['sex', 'day'], as_index=False).sum() fig = make_subplots(rows=1,

cols=2,

subplot_titles=[

'Erkekler', # 1. subplot title

'Kadınlar' # 2. subplot title

])

fig.add_trace(go.Bar(x=grouped_df[grouped_df['sex'] == 'Male']['day'], y=grouped_df[grouped_df['sex'] == 'Male']['tip'], name='Male'),row=1, col=1)

fig.add_trace(go.Bar(x=grouped_df[grouped_df['sex'] == 'Female']['day'], y=grouped_df[grouped_df['sex'] == 'Female']['tip'], name='Female'), row=1, col=2)

fig.update_layout(title='Günlere Göre Toplam Bahşişler', title_x=0.5)

So what happened above? Firstly we created a parsed grid. But unlike previous we gave subplot_titles parameter. Because of that our graphs was be owner their own titles. Please remember, title parameter is which in update_layout is not coming from sub_plots. It’s from Plotly figure. So that parameter just affects main grid.

Share X Axis for each Graph

We can share x or y axis for each plots. We’ll do it in this example for x axis. We need to use shared_xaxes=True parameter in the make_subplots function. If want to share y axis, we can use shared_yaxis=True parameter like same thing. Again we’ll use same dataset but our figure create style won’t be like previous. We’ll use for loop for each category and grid will be 2 x 1 in this example.

grouped_df = df.groupby(['sex', 'day'], as_index=False).sum() fig = make_subplots(rows=len(grouped_df['sex'].unique()), cols=1, shared_xaxes=True)

We created a subplot grid which the row number counted by every unique category length. So we’ll have a new row for each unique value.

row = 1

for trace in grouped_df['sex'].unique():

fig.add_trace(go.Bar(x=grouped_df[grouped_df['sex'] == trace['day'], y=grouped_df[grouped_df['sex'] == trace]['tip'], name=trace), row=row, col=1)

row += 1

We created a row variable for aligning graphs with using row number. We setted 1 for its value. Because in subplots index is not like list’s index. It starts from 1. After that we added a trace for each unique sex value and we setted their row and column numbers. As seen in the picture, we shared x axis for each graph.

Figure with shared x axis for each graphs

Plot Layering

We can say for plot layering, it occurs by over and over creating graphs in the same figure. We don’t need to parse grids. We’ll use again add_trace function for doing it. We will use same dataset and grouped dataframe.

grouped_df = df.groupby(['sex', 'day'], as_index=False)a.sum() fig = go.Figure() # create empty figure fig.add_trace(go.Bar(x=grouped_df[grouped_df['sex']=='Male']['day'], y=grouped_df[grouped_df['sex']=='Male']['tip'],name='Male'))

Firstly we created an empty figure. After that we added one bar graph on it. If execute it, we’ll see this output.

And now we suppose, we want to add a line chart on this bar chart. I’ll use again same technique, add_trace.

fig.add_trace(go.Scatter(x=grouped_df[grouped_df['sex']=='Female']['day'], y=grouped_df[grouped_df['sex']=='Female']['tip'],mode='lines+markers',name='Female')) fig.show()

And now if execute this code, we’ll see this output. So we layered our plot.

You can access the codes from my GitHub repo. I hope it’ll be helpful. Kind regards.