close

How to plot multiple lines on the same y-axis using Plotly Express in Python

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to plot multiple lines on the same y-axis using Plotly Express in Python in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

How to plot multiple lines on the same y-axis using Plotly Express in Python?

  1. How to plot multiple lines on the same y-axis using Plotly Express in Python?

    Where df.columns are the column names of the columns returned as a list, or a subset of the columns using, for example, df.columns[1:-6]

  2. plot multiple lines on the same y-axis using Plotly Express in Python

    Where df.columns are the column names of the columns returned as a list, or a subset of the columns using, for example, df.columns[1:-6]

Method 1

fig = px.line(df, x='Date', y=df.columns[1:-6])

Where df.columns are the column names of the columns returned as a list, or a subset of the columns using, for example, df.columns[1:-6]


The details

Your code works fine But if you specifically do not want to apply the (somewhat laborious) add_trace() function to each line, you can use px.line(). This used to require you to transform your data from a wide to long format. But not anymore, so just define an index and name the columns you’d like to plot. Or reference all or a subset of your dataframe columns through, for ecxample, y=df.columns[1:-6]

# imports
import plotly.express as px 
import pandas as pd 
import numpy as np 

# data
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
fig = px.line(df, x='Date', y=df.columns[1:-6])

# Show plot 
fig.show()

Plot:

enter image description here

If you’d like to know how to do the same thing with data of a long format, here’s how you do that too using pandas and plotly:

# imports
import plotly.express as px 
import pandas as pd 
import numpy as np 

# data
df_wide = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')
df_long=pd.melt(df_wide, id_vars=['Date'], value_vars=['AAPL.Open', 'AAPL.High', 'AAPL.Low', 'AAPL.Close', 'mavg'])

# plotly 
fig = px.line(df_long, x='Date', y='value', color='variable')

# Show plot 
fig.show()

Method 2

Not sure what type of line your looking for, but have you tried something like below

fig.add_scatter(x=df['Date'], y=df['AAPL.Low'],mode='lines')

On a standard scatter you can set the mode to be any combination of lines, markers and text.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read