Layering Plots
Learn to extend your knowledge of subplots with layering plots over the top of each other, rather than next to each other.
We'll cover the following...
Layering plots in Plotly
We have seen how to place multiple traces on the same graph, but here we discuss some important nuances.
We will use a dataset of the stock price of Qantas:
Press + to interact
# Import librariesimport pandas as pdimport numpy as np# Import datasetsqantas = pd.read_csv('/usr/local/csvfiles//qantas.csv', parse_dates=['Date'])print(qantas.head())
Layering plots in awkward scenarios
In this example, we are interested in the closing price, as well as the 100 and 250-day moving averages for the closing price, stored in the RollingClose_100
and RollingClose_250
variables, respectively.
In Plotly graph objects, we can create multiple traces and easily plot each series on a single figure using the following code, seen below:
Press + to interact
# Import librariesimport pandas as pdimport numpy as npimport plotly.express as pximport plotly.graph_objects as gofrom plotly.subplots import make_subplots# Import datasetqantas = pd.read_csv('/usr/local/csvfiles//qantas.csv', parse_dates=['Date'])# Make traces and addtrace1 = go.Scatter(x=qantas['Date'], y=qantas['Close'], name='Close')trace2 = go.Scatter(x=qantas['Date'], y=qantas['RollingClose_100'], name='100 Day Moving Average')trace3 = go.Scatter(x=qantas['Date'], y=qantas['RollingClose_250'], name='250 Day Moving Average')fig = go.Figure(data=[trace1, trace2, trace3])fig.update_layout(title='Qantas Stock Prices')fig.show()
In Plotly Express it is even easier: We can simply pass multiple columns to the y
argument inside px.line
...