10

I would like to have a multiple line plot within same canvas tied with the same x-axis as shown something in the figure:

enter image description here

Using subplots does not achieve the intended desire.

import plotly.express as px
from plotly.subplots import make_subplots
import plotly.graph_objects as go

fig = make_subplots(rows=2, shared_xaxes=True,vertical_spacing=0.1)
fig.add_scatter(y=[2, 1, 3], row=1, col=1)
fig.add_scatter(y=[1, 3, 2], row=2, col=1)
fig.show()

May I know how this can be done, appreciate if someone can point to good reading material

2 Answers 2

16

With a dataset such as this you can select any number of columns, set up a figure using fig = make_subplots() with shared_xaxes set to True and then add your series with a shared x-axis using fig.add_trace(go.Scatter(x=df[col].index, y=df[col].values), row=i, col=1) in a loop to get this:

enter image description here

Let me know if this is a setup you can use but need a little tweaking.

Complete code:

import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
import pandas as pd

# data
pio.templates.default = "plotly_white"
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
df = df.set_index('Date')
df.tail()
cols = df.columns[:-4]
ncols = len(cols)

# subplot setup
fig = make_subplots(rows=ncols, cols=1, shared_xaxes=True)

for i, col in enumerate(cols, start=1):
    fig.add_trace(go.Scatter(x=df[col].index, y=df[col].values), row=i, col=1)
    
fig.show()
Sign up to request clarification or add additional context in comments.

Comments

3

Depending on the data you are plotting, I think you could either check out "Stacked Subplots with a Shared X-Axis (low-level API)" on https://plotly.com/python/subplots/

Or separate the data by shifting each line plot upwards like so:

import plotly.graph_objects as go
import random


data = []
n = 9

for x in range(10, 60, 10):

  points = [value + x for value in random.sample(range(1,n+1), k = n)]
  
  data.append(go.Scatter(y=points))

fig = go.Figure(data = data)

fig.show()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.