2 Plots- Same X axis - Different Y axis -Merge them to Same file

Hi,
I am rephrasing the same question which i have asked before, sorry for the confusion.
I have 2 csv files, in which the x axis data is same. In file1 the y axis value will start from 0 and will go till positive 200. In file2 the y axis value will be between -20 to +20. In both file1 and file2 the x axis data is date. trace names are same as well. So i had decided to create 2 separate html files for each file.
But now i am in need of displaying them in one html file, but they have 2 different y- axis . How can i get this done in plotly. I want the legend to be common and i want to display both data while i hover the x-axis.
Since i am using plotly once in a month or 2 months, i might not be familiar with some terms, kindly apologise if i am not clear. Any help would be appreciated.

Heyo!

Just use a dual y-axis! Basically you have to add to the layout and define a separate axis for each trace, as shown here:

@louisrivers thanks for the reply, i have 2 file sources, so i have 2 functions that return me fig How can i combine them for creating this plot.

@rasika

This is the use case you should have given:

import numpy as np
import datetime
import pandas as pd
import plotly.graph_objects as go

date = [datetime.date(year=2019, month=10, day=1),
        datetime.date(year=2019, month=10, day=2),
        datetime.date(year=2019, month=10, day=3),
        datetime.date(year=2019, month=10, day=4),
        datetime.date(year=2019, month=10, day=5),
        datetime.date(year=2019, month=10, day=6),
        datetime.date(year=2019, month=10, day=7),
        datetime.date(year=2019, month=10, day=8)]


df = pd.DataFrame({'date': date, 'y1':np.random.randint(0,201, 8), 'y2': np.random.randint(-20,21, 8)})

fig1 =go.Figure([go.Scatter(x=df['date'], y=df['y1'], name='trace_name')])
fig2 =go.Figure([go.Scatter(x=df['date'], y=df['y2'], name='trace_name')])

Now to merge the two figures in a single plot just define a subplot with 1 row and 1 column, for which you give the secondary_y=True, i.e. you inform plotly.js that your plot will have two y axes and the same xaxis:

from plotly.subplots import make_subplots
fig = make_subplots(specs=[[{"secondary_y": True}]])
fig.add_trace(fig1.data[0], secondary_y=False)
fig.add_trace(fig2.data[0], secondary_y=True)
fig.update_layout(width=700, height=450, hovermode='x')
fig.show()

If your fig1 or fig2 contains many traces, i.e. len(fig1.data)>1, then you you have to add each trace to the new fig.

1 Like

Thank you, this works, How can i fix the axis layout for each of these figures.

@rasika

You can update the layout
through:

fig.update_layout(xaxis = dict(your settings),
yaxis=dict(your settings), yaxis2=dict(your settings))

yaxis is the left y-axis, while yaxis2 is the right one.

1 Like

Got it working, thanks