How to create subplots with Python Plotly?


Plotly is an open-source Python library that is used for data visualization. It supports various types of charts. In this tutorial, we will show how you can show multiple plots on a single chart.

  • Here we will use plotly.graph_objects to generate figures. It contains a lot of methods to customize the charts and render them into HTML format.

  • We will use the method make_subplots to add subplots.

Follow the steps given to create subplots with Python Plotly.

Step 1

Import the plotly.graphs_objs module and alias as go.

import plotly.graphs_objs as go

Step 2

Import make_subplots to create subplots

from plotly.subplots import make_subplots

Step 3

Create a dataframe using the following coordinates −

data = {
   'x':['a','b','c'],
   'y':['d','e','f'],
   'z':['a','e','i']
}
df = pd.DataFrame(data)

Step 4

Create two scatter plots and store them in the variables first_line and second_line.

first_line = go.Scatter(x=df["x"], y=df["y"], name="one")
second_line = go.Scatter(x=df["x"], y=df["z"], name="two")

Step 5

Set the make_subplots() method with rows and cols and shared_yaxes.

fig = make_subplots(rows=1, cols=3, shared_yaxes=True)

Example

The complete code to create subplots is as follows −

import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd data = { 'x':['a','b','c'], 'y':['d','e','f'], 'z':['a','e','i'] } df = pd.DataFrame(data) first_line = go.Scatter(x=df["x"], y=df["y"], name="First Plot") second_line = go.Scatter(x=df["x"], y=df["z"], name="Second Plot") fig = make_subplots(rows=1, cols=3, shared_yaxes=True, horizontal_spacing=0.10) fig.add_trace(first_line, row=1, col=1) fig.add_trace(second_line, row=1, col=2) fig.update_layout(height=400, width=716, title_text="Creating Subplots in Plotly") fig.show()

Output

On execution, it will produce the following chart on the browser −


We have used the horizontal_spacing attribute of the make_subplots() method to provide spacing between the two subplots.

Updated on: 21-Oct-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements