Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add several graphs to a single tab using plotly express with python

I have a script that producing 5 different graphs that I want to present in one web page. I use python with plotly express and define pio.renderers.default = "browser". The problem is that each graph is open in a new tab, and I want only one tab that I could share. My script contains two separate data frames:

import pandas as pd
import plotly.express as px
import plotly.io as pio
pio.renderers.default = "browser"

df1=pd.read_csv('data1.csv')
df2=pd.read_csv('data2.csv')

fig = px.bar(df1,x1, y1,color='a',barmode='group')
fig.show()   
fig = px.line(df2,x2, y2,color='b')
fig.show()   
like image 676
Shely Avatar asked May 03 '26 21:05

Shely


1 Answers

OK, you need to use plotly.subplots.make_subplots. I don't have your data, so I will use a simple data from plotly in the following code:

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

df = px.data.gapminder().query("country == 'Canada'")
fig1 = px.bar(df, x='year', y='pop')
fig2 = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')

fig = make_subplots(rows=2, cols=1, shared_xaxes=False)
fig.add_trace(fig1['data'][0], row=1, col=1)
fig.add_trace(fig2['data'][0], row=2, col=1)
fig.show()

This will generate the following graph: enter image description here

Side Note: Plotly.express shows figure in the browser by default, you don't have to specify it.

like image 154
Anwarvic Avatar answered May 06 '26 10:05

Anwarvic