Thank you derflo and vestland! I really wanted to use Plotly Express as opposed to Graph Objects with dual axis to more easily handle DataFrames with lots of columns. I dropped this into a function. Data1/2 works well as a DataFrame or Series.
import plotly.express as px
from plotly.subplots import make_subplots
import pandas as pd
def plotly_dual_axis(data1,data2, title="", y1="", y2=""):
# Create subplot with secondary axis
subplot_fig = make_subplots(specs=[[{"secondary_y": True}]])
#Put Dataframe in fig1 and fig2
fig1 = px.line(data1)
fig2 = px.line(data2)
#Change the axis for fig2
fig2.update_traces(yaxis="y2")
#Add the figs to the subplot figure
subplot_fig.add_traces(fig1.data + fig2.data)
#FORMAT subplot figure
subplot_fig.update_layout(title=title, yaxis=dict(title=y1), yaxis2=dict(title=y2))
#RECOLOR so as not to have overlapping colors
subplot_fig.for_each_trace(lambda t: t.update(line=dict(color=t.marker.color)))
return subplot_fig
UPDATE:
This is great for creating a plot with dual axis, but I also wanted to call out the behavior of gridlines and zero points. These y-axis are totally separate. So by default, the zero points will not align (see red box) and neither will the gridlines:
You may be able to align the zeroes fairly easily by utilizing rangemode = 'tozero'
in your yaxis dictionaries when applying a layout. See the layout-yaxis Plotly Documentation. However, this won't work if you have negative values.
The good folk at plotly are currently working on gridline alignment. There are some great examples of this at work in this Github repo.