new using Dash and need to plot multiple plotly traces in a single plot using a date picker component. Looking for examples that show how to:
- automatically plot the full data range as default upon loading before any date range is selected.
- update the single plot frame (both traces) when the date range is selected.
Right now the date picker works, but the plot is blank until a date range is selected. As well, when the date range is selected, the plot overlays the full data underneath the selected data.
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)