I’ve got two tabs in my applications and each one of them has a graph, a dropdown and a callback that updates the graph. The problem is that when I go to the second tab and try to update the graph, I’m automatically taken to the first tab which is the default and then I have to click on the second tab again to see the chages. Why is this happening? Am I doing something wrong or that’s a bug in Dash? Any help will be appreciated. Thanks.
My code:
import dash
import dash_html_components as html
import dash_core_components as dcc
import pandas as pd
from dash.dependencies import Input, Output
import plotly.graph_objs as go
app = dash.Dash()
df = pd.read_csv('gapminderDataFiveYear.csv')
year_options = []
for year in df['year'].unique():
year_options.append({'label':str(year),'value':year})
# Create a Dash layout
app.layout = html.Div([
html.Div(
html.H1('My Dashboard')
),
dcc.Tabs(id="tabs", value='Tab1', children=[
dcc.Tab(label='Tab 1', id='tab1', value='Tab1', children =[
dcc.Graph(id='graph-1'),
dcc.Dropdown(id='year-picker-1', options=year_options, value=df['year'].min())
]),
dcc.Tab(label='Tab 2', id='tab2', value= 'Tab2', children=[
dcc.Graph(id='graph-2'),
dcc.Dropdown(id='year-picker-2', options=year_options, value=df['year'].min())
])
])
])
@app.callback(Output('graph-1', 'figure'),
[Input('year-picker-1', 'value')])
def update_figure_1(selected_year):
filtered_df = df[df['year'] == selected_year]
traces = []
for continent_name in filtered_df['continent'].unique():
df_by_continent = filtered_df[filtered_df['continent'] == continent_name]
traces.append(go.Scatter(
x=df_by_continent['gdpPercap'],
y=df_by_continent['lifeExp'],
text=df_by_continent['country'],
mode='markers',
opacity=0.7,
marker={'size': 15},
name=continent_name
))
return {
'data': traces,
'layout': go.Layout(
xaxis={'type': 'log', 'title': 'GDP Per Capita'},
yaxis={'title': 'Life Expectancy'},
hovermode='closest'
)
}
@app.callback(Output('graph-2', 'figure'),
[Input('year-picker-2', 'value')])
def update_figure_1(selected_year):
filtered_df = df[df['year'] == selected_year]
traces = []
for continent_name in filtered_df['continent'].unique():
df_by_continent = filtered_df[filtered_df['continent'] == continent_name]
traces.append(go.Scatter(
x=df_by_continent['gdpPercap'],
y=df_by_continent['lifeExp'],
text=df_by_continent['country'],
mode='markers',
opacity=0.7,
marker={'size': 15},
name=continent_name
))
return {
'data': traces,
'layout': go.Layout(
xaxis={'type': 'log', 'title': 'GDP Per Capita'},
yaxis={'title': 'Life Expectancy'},
hovermode='closest'
)
}
if __name__ == '__main__':
app.run_server(debug=True)