Brand new to using Python Dash. I have a dual trace plot and I need it to:
- Display the full data range upon loading.
- Update both traces when a date range is selected.
I’m using plotly GO to generate the two traces using a test dataframe with a datetime index and a datepicker component.
Right now the plot is blank until a date range is selected and both the full and selected data ranges are plotted.
What do I need to correct to display the full date range as default and update the plot without showing overlapping traces?
many thanks
import pandas as pd
from dash import Dash, html, dcc
from dash.exceptions import PreventUpdate
import plotly.graph_objects as go
from dash.dependencies import Input, Output
from plotly.subplots import make_subplots
# initialize the dash app as 'app'
app = Dash(__name__)
population_1=1e7+50*np.arange(61)
population_2=1e8+5*np.arange(61)**2
test_df=pd.DataFrame(data={'pop 1':population_1, 'pop 2': population_2})
test_df.index=pd.date_range(start='2000-01-01', end='2000-03-01')
# use specs parameter in make_subplots function
# to create secondary y-axis
fig = make_subplots(specs=[[{"secondary_y": True}]])
# plot a scatter chart by specifying the x and y values
# Use add_trace function to specify secondary_y axes.
fig.add_trace(
go.Scatter(x=test_df.index, y=test_df['pop 1'], name="pop 1"),
secondary_y=False)
# Use add_trace function and specify secondary_y axes = True.
fig.add_trace(
go.Scatter(x=test_df.index, y=test_df['pop 2'], name="pop 2"),
secondary_y=True,)
beginning_date=test_df.index[0]
ending_date=test_df.index[-1]
# set up the app layout
app.layout = html.Div(children=
[
html.H1(children=['Test Daframe Dashboard']),
html.Div(children=['Population plotting with year picker']),
dcc.DatePickerRange(
id='my-date-picker-range',
min_date_allowed=beginning_date,
max_date_allowed=ending_date
),
dcc.Graph(id='population-plot',figure={}),
]
)
@app.callback(
Output('population-plot', 'figure'),
Input('my-date-picker-range', 'start_date'),
Input('my-date-picker-range', 'end_date'))
def update_output(start_date, end_date):
print (start_date, end_date)
if not start_date or not end_date:
raise PreventUpdate
else:
output_selected_df=test_df.loc[(test_df.index>=start_date)&(test_df.index<=end_date),:]
fig.add_trace(
go.Scatter(x=output_selected_df.index, y=output_selected_df['pop 1'], name="pop 1"),
secondary_y=False)
# Use add_trace function and specify secondary_y axes = True.
fig.add_trace(
go.Scatter(x=output_selected_df.index, y=output_selected_df['pop 2'], name="pop 2"),
secondary_y=True,)
return fig
if __name__=='__main__':
app.run(debug=True)