How can I set rangeselector() buttons to zoom in on pre-defined date ranges for a time series plot? For example, I’m looking at stock market data for 2020 YTD, and I’d like to have two buttons “The Bull Run” and “the Crash”, which refer to the datetime ranege Bullrun=[2020-01-03 to 2020-02-19] and Crash=[2020-02-20 - 2020-05-06], and when I click on those buttons (instead of it being say “Last 6mo” or “YTD”), i want the plot to zoom in on those time periods specifically. Thank you.
Hi @tjf2007 welcome to the forum! For this you can use a normal layout button which modifies the xaxis range, like in the example below. For more details please refer to the tutorial on layout buttons
import plotly.graph_objects as go
import pandas as pd
# Load data
df = pd.read_csv(
"https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")
df.columns = [col.replace("AAPL.", "") for col in df.columns]
# Create figure
fig = go.Figure()
fig.add_trace(
go.Scatter(x=list(df.Date), y=list(df.High)))
# Set title
fig.update_layout(
title_text="Time series with range slider and selectors"
)
# Add range slider
fig.update_layout(
xaxis=dict(
rangeslider=dict(
visible=True
),
type="date",
range=('2015-04-01', '2017-01-01')
)
)
fig.update_layout(
updatemenus=[
dict(
type="buttons",
buttons=[
dict(label="Custom",
method="relayout",
args=["xaxis", {'range':('2015-07-01', '2015-09-01'),
'rangeslider':dict(visible=True),}]),]
)]
)
fig.show()
Note that with the button your modifying all xaxis attributes so if you want some of them to persist (as with the rangeslider) you need to pass them along in the args
.
In fact a simpler syntax is to pass directly xaxis.range
in the args
as in
import plotly.graph_objects as go
import pandas as pd
# Load data
df = pd.read_csv(
"https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv")
df.columns = [col.replace("AAPL.", "") for col in df.columns]
# Create figure
fig = go.Figure()
fig.add_trace(
go.Scatter(x=list(df.Date), y=list(df.High)))
# Set title
fig.update_layout(
title_text="Time series with range slider and selectors"
)
# Add range slider
fig.update_layout(
xaxis=dict(
rangeslider=dict(
visible=True
),
type="date",
range=('2015-04-01', '2017-01-01')
)
)
fig.update_layout(
updatemenus=[
dict(
type="buttons",
buttons=[
dict(label="Custom",
method="relayout",
args=["xaxis.range", ('2015-07-01', '2015-09-01'),]),]
)]
)
fig.show()