Trying to Run Multiple Dash (by Plotly) Apps in One Page - python

Greetings = I'm trying to build multiple Dash (by Plotly) Apps in One Page. In other words, the user sees a data visualization on top of the page, scrolls down, sees some sample text, scrolls down and then sees another data visualization. The code runs but only the second data visualization populates (along with the sample text). Any help would be greatly appreciated.
Here is the sample code:
import plotly.plotly as py
import plotly.graph_objs as go
import numpy as np
import pandas as pd
import requests
import io
import re
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from app import server
app = dash.Dash('dash_36', sharing=True, url_base_pathname='/dash_36',
csrf_protect=False, server=server)
app.config['suppress_callback_exceptions']=True
df = pd.read_csv('app_8/main.csv')
colors = {
'background': '#111111',
'text': '#7FDBFF'
}
app.layout = html.Div([
html.A("Previous Chart: ", href='dash_16'),
html.A(" Next Chart:", href='dash_18'),
html.A(" Back to Main Page:",
href='https://ds.org/index'),
dcc.Graph(
id='Senators of the United States 115th Congress: '
'America ~ A Country Up For $ALE',
figure={
'data': [
go.Scatter(
x=df[df['party'] == i]['sector_total'],
y=df[df['party'] == i]['industry_total'],
#z=df[df['candidate_name'] == i]['contributor_total'],
text=df[df['party'] == i]['candidate_name'],
mode='markers',
opacity=0.7,
marker={
'size': 15,
'line': {'width': 0.5, 'color': 'white'}
},
name=i
) for i in df.party.unique()
],
'layout': go.Layout(
xaxis={'title': 'Sector Total'},
yaxis={'title': 'Industry Total'},
#margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
#legend={'x': 0, 'y': 1},
hovermode='closest',
title='Sector Total, Industry Total & Candidate Name by
Party',
plot_bgcolor= colors['background'],
paper_bgcolor=colors['background'],
height=700,
font= {
'color': colors['text'],
}
)
}
),
dcc.Markdown('''
# SAMPLE TEXT
# This is an <h1> tag
## This is an <h2> tag
###### This is an <h6> tag
'''),
dcc.Markdown('''
*This text will be italic*
_This will also be italic_
**This text will be bold**
__This will also be bold__
_You **can** combine them_
'''),
dcc.Graph(
id='Senators of the United States 115th Congress: '
'America ~ A Country Up For $ALE',
figure={
'data': [
go.Scatter(
x=df[df['contributor_name'] == i]
['contributor_individual'],
y=df[df['contributor_name'] == i]['contributor_pac'],
#z=df[df['candidate_name'] == i]['contributor_total'],
text=df[df['contributor_name'] == i]['candidate_name'],
mode='markers',
opacity=0.7,
marker={
'size': 15,
'line': {'width': 0.5, 'color': 'white'}
},
name=i
) for i in df.contributor_name.unique()
],
'layout': go.Layout(
xaxis={'title': 'Contributor Individual'},
yaxis={'title': 'Contributor PAC'},
#margin={'l': 10, 'b': 10, 't': 10, 'r': 10},
#legend={'x': 0, 'y': 1},
hovermode='closest',
title='Contributor Individual, Contributor PAC & Candidate
Name by Contributor Name',
plot_bgcolor= colors['background'],
paper_bgcolor=colors['background'],
height=700,
font= {
'color': colors['text'],
}
)
}
)
])

The idea is to have two different script for each dash and then use another script who makes the connection. You can follow this tutorial: multiple dash
At the end there is an example.

Related

Dash leaflet not rendering when inside a Bootstrap tab container

I am trying to create a simple Dash application that includes Dash-Leaflet so that it plots some points as markers. It is apparently working as expected when no styles are applied. But I would like to create a layout with bootstrap with tabs as in this example: https://hellodash.pythonanywhere.com/
When I place the map element within a tab container, it does not render properly. If I move it away it works fine.
This is the code I have so far:
from dash import Dash, dcc, html, dash_table, Input, Output, callback
import plotly.express as px
import dash_bootstrap_components as dbc
import dash_leaflet as dl
import dash_leaflet.express as dlx
from dash_extensions.javascript import assign
import pandas as pd
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
header = html.H4(
"Sample map", className="bg-primary text-white p-2 mb-2 text-center"
)
data = pd.DataFrame([{'name': 'Point 1', 'lat': 39.535, 'lon': 0.0563, 'cluster': 1, 'val_x': 0, 'val_y': 1},
{'name': 'Point 2', 'lat': 40.155, 'lon': -0.0453, 'cluster': 1, 'val_x': 1, 'val_y': 4},
{'name': 'Point 1', 'lat': 38.875, 'lon': 0.0187, 'cluster': 2, 'val_x': 2, 'val_y': 2}])
dropdown = html.Div(
[
dbc.Label("Select Cluster"),
dcc.Dropdown(
data.cluster.unique().tolist(),
id="cluster_selector",
clearable=False,
),
],
className="mb-4",
)
controls = dbc.Card(
[dropdown],
body=True,
)
tab1 = dbc.Tab([dl.Map([dl.TileLayer()], style={'width': '100%',
'height': '50vh',
'margin': "auto",
"display": "block"}, id="map")], label="Map")
tab2 = dbc.Tab([dcc.Graph(id="scatter-chart")], label="Scatter Chart")
tabs = dbc.Card(dbc.Tabs([tab1, tab2]))
app.layout = dbc.Container(
[
header,
dbc.Row(
[
dbc.Col(
[
controls,
],
width=3,
),
dbc.Col([tabs], width=9),
]
),
],
fluid=True,
className="dbc",
)
if __name__ == "__main__":
app.run_server(debug=True, port=8052)
This is what it looks like.
I have tried the proposed solutions on this post but they do not seem to work (or I am applying the wrong)
Do you have any suggestions on where to look for the problem?
Thank you very much.

JupyterDash - Invalid argument `options` passed into Dropdown with ID

I am trying to create a dashboard to show the ethnicity makeup in different cities for multiple years. My dataframe consists of Year, Month, City and Native variables. I pasted an image on the bottom that shows my dataframe. I also tried to replicate a Dash code that I have but I received multiple errors after executing it, and it looks like most of the errors are about the City variable. Is there any guide to get my dash to work?
import dash
from jupyter_dash import JupyterDash # pip install dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
#df
import dash
from jupyter_dash import JupyterDash # pip install dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
#df
app = JupyterDash()
app.layout = html.Div([
html.H1("Native Country of Father"),
dcc.Dropdown(
id='cities',
options=[{'label': i, 'value': i} for i in list(df.City.unique()) + ['All']],
value='All'
),
dcc.RadioItems(
id='xaxis-type',
options=[{'label': i, 'value': i} for i in ['Linear', 'Log']],
value='Log',
labelStyle={'display': 'inline-block'}
),
dcc.Graph(id='graph-with-slider'),
dcc.Slider(
id='year-slider',
min=df['Year'].min(),
max=df['Year'].max(),
value=df['Year'].min(),
step=None,
marks={str(Year): str(Year) for Year in df['Year'].unique()}
)
],
style={'width': '48%', 'display': 'inline-block'})
#app.callback(
Output('graph-with-slider', 'figure'),
[Input('year-slider', 'value'),
Input('xaxis-type','value'),
Input('cities','value')])
def update_figure(selected_year, axis_type, City):
if City=="All":
filtered_df = df
else:
filtered_df = df[df['City']==City]
filtered_df = filtered_df[filtered_df.Year == selected_year]
traces = []
for i in filtered_df.City.unique():
df_by_City = filtered_df[filtered_df['City'] == i]
traces.append(go.Scatter(
y=df_by_City['Native Country of Father'],
text=df_by_City['Native Country of Father'],
mode='markers',
opacity=0.7,
marker={
'size': 15,
'line': {'width': 0.5, 'color': 'white'}
},
name=i
))
return {
'data': traces,
'layout': go.Layout(
xaxis={'type': 'linear' if axis_type == 'Linear' else 'log',
'title': 'GDP Per Capita'},
yaxis={'title': 'Life Expectancy', 'range': [20, 90]},
margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
legend={'x': 0, 'y': 1},
hovermode='closest'
)
}
if __name__ =='__main__':
app.run_server(mode="external")
To get the dropdown working properly, you'll have to fix the value passed to options. What you have is:
options=[{'label': i, 'value': i} for i in list(df.City.unique()) + ['All']]
If you remove ['All'] and change the value prop, it should work. In order to have a value that selects everything, you need something like
options=[
{'label': i, 'value': i} for i in list(df.City.unique())
] + [{'label': 'All', 'value': 'All'}]

Plotly Dash: How to prevent Figure from appearing when no dropdown value is selected?

I'm building a dashboard (code below) and my goal is to show several key facts about the data on a country-level basis. For example, current population vs. average population of all countries, life expectation vs. average life expectation of all countries etc.
I don't want to display the graph when no country (i.e. no dropdown option) is selected. This should also be standard when first launching the dashboard. However, I receive an error message when either clearing the dropdown or setting the value to '' in the layout area.
Does anybody know any solution to this problem?
import pandas as pd
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import plotly.express as px
import plotly.graph_objects as go
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')
fig = go.Figure()
# create the Dash app
app = dash.Dash()
# set up app layout
app.layout = html.Div(children=[
html.H1(children='Demographic Statistics'),
dcc.Dropdown(id='country-dropdown',
options=[{'label': x, 'value': x}
for x in df.country.unique()],
value='Argentina',
multi=False, clearable=True),
dcc.Graph(id='indicators', figure=fig)
])
# set up the callback function
#app.callback(
Output('indicators', 'figure'),
[Input('country-dropdown', 'value')])
def display_demographic_statistics(selected_country):
filtered_country = df[df.country == selected_country]
pop_confirmed = df.loc[df['country'] == selected_country, 'pop'].iloc[0]
lifexp = df.loc[df['country'] == selected_country, 'lifeExp'].iloc[0]
average_confirmed = df["pop"].mean()
average_lifexp = df["lifeExp"].mean()
return {
'data': [go.Indicator(
mode='number+delta',
value=pop_confirmed,
delta={'reference': average_confirmed,
'position': 'right',
'valueformat': ',g',
'relative': False,
'font': {'size': 15}},
number={'valueformat': ',',
'font': {'size': 20},
},
domain={'y': [0, 1], 'x': [0, 1]})],
'layout': go.Layout(
title={'text': 'Demgraphic Statistics'},
grid = {'rows': 2, 'columns': 2, 'pattern': "independent"},
template = {'data' : {'indicator': [{
'mode' : "number+delta+gauge",
'delta' : {'reference': 90}}]}}
),
}
# Run local server
if __name__ == '__main__':
app.run_server(debug=True, use_reloader=False)
You could make the component with id='indicators' an html.Div and use the callback to update its children property as follows:
if the user selects a country from the dropdown, then the callback returns
a dcc.Graph with the indicators for the selected country,
if the user clears the dropdown, then the callback returns None (i.e. nothing).
Note also that the value of the dropdown when no selection has been made is None, not ''.
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')
app = dash.Dash()
app.layout = html.Div(children=[
html.H1(children='Demographic Statistics'),
dcc.Dropdown(
id='country-dropdown',
options=[{'label': x, 'value': x} for x in df.country.unique()],
value=None,
multi=False,
clearable=True
),
html.Div(id='indicators')
])
#app.callback(
Output('indicators', 'children'),
[Input('country-dropdown', 'value')])
def display_demographic_statistics(selected_country):
if selected_country is not None:
pop_confirmed = df.loc[df['country'] == selected_country, 'pop'].iloc[0]
average_confirmed = df['pop'].mean()
return dcc.Graph(
figure=go.Figure(
data=go.Indicator(
mode='number+delta',
value=pop_confirmed,
delta={
'reference': average_confirmed,
'position': 'right',
'valueformat': ',g',
'relative': False,
'font': {'size': 15}
},
number={
'valueformat': ',',
'font': {'size': 20},
},
domain={
'y': [0, 1],
'x': [0, 1]
}
),
layout=go.Layout(
title={'text': 'Demgraphic Statistics'},
grid={'rows': 2, 'columns': 2, 'pattern': 'independent'},
template={'data': {'indicator': [{'mode': 'number+delta+gauge', 'delta': {'reference': 90}}]}}
)
)
)
else:
return None
if __name__ == '__main__':
app.run_server(host='127.0.0.1', debug=True)

Python Dash - Graph not updating upon selecting new dropdown value

Hey guys,
I’m an intern python developer and I just found out about dash and Plotly, its amazing!
For my app I’m using a dataset containing info about fortune 500’s revenue in 1955-2005 period.
The problem I have is that the graph won’t update itself upon selecting additional company from the dropdown list, however, if I select a new company and delete a previous one - then the graph updates. It seems like something prevents the graph to show multiple lines at once. Also, is there any way I could add the legend telling which color is what company? Below is my code:
import dash
import dash_html_components as html
import dash_core_components as dcc
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output
#Read CSV and change col. names
df = pd.read_csv('fortune500-full.csv')
df.columns = ['Year', 'Rank', 'Company', 'Revenue', 'Profit']
#Get a list of unique company names
Companies = df['Company'].unique()
#Stylesheet
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
#App layout
app.layout = html.Div([
#Dropdown
html.Div([
html.Label('Dropdown'),
dcc.Dropdown(
id = 'Dropdown',
options=[{'label': i, 'value': i} for i in Companies],
value=["General Motors"],
multi = True
),]),
#Graph
dcc.Graph(
id='Graph',
figure={
'data': [
go.Scatter(
x=df.loc[df['Company'] == i, 'Year'],
y=df.loc[df['Company'] == i, 'Revenue'],
text =df.loc[df['Company'] == i, 'Company'],
mode='lines',
name=i
) for i in df.Company.unique()],
'layout': go.Layout(
xaxis={'title': 'Year'},
yaxis={'title': 'Revenue'},
margin={'l': 50, 'b': 30, 't': 10, 'r': 0},
legend={'x': 1, 'y': 1},
hovermode='closest'
)}),
html.Div(dcc.RangeSlider(
id='Slider',
min=df['Year'].min(),
max=df['Year'].max(),
value=[1955, 2005],
marks={str(year): str(year) for year in df['Year'].unique()}
), style={'width': '98%', 'padding': '0px 20px 20px 20px'}),
html.Div(id='Output_slider',
style={'textAlign': 'center', 'color': ['#7FDBFF']}
)])
#app.callback(
dash.dependencies.Output('Graph', 'figure'),
[dash.dependencies.Input('Dropdown', 'value')])
def callback_a(dropdown_value):
trace = []
for val in dropdown_value:
trace.append(
go.Scatter(
x=df.loc[df['Company'] == val, 'Year'],
y=df.loc[df['Company'] == val, 'Revenue'],
text =df.loc[df['Company'] == val, 'Company'],
mode='lines',
name=val
),)
layout = go.Layout(
xaxis={'title': 'Year'},
yaxis={'title': 'Revenue'},
margin={'l': 50, 'b': 30, 't': 10, 'r': 0},
legend={'x': 1, 'y': 1},
hovermode='closest'
)
figure = {'data': trace, 'layout': layout}
return figure
#app.callback(
dash.dependencies.Output('Output_slider', 'children'),
[dash.dependencies.Input('Slider', 'value')])
def update_output(value):
return 'Wybrane lata: "{}"'.format(value)
#App
if __name__ == '__main__':
app.run_server(debug=True)
Could any of you please take a look at this and help me find root of this problem?
Kind regards.

Python - Lowess regression integration for Plotly Dash

I am attempting to create an interactive graph inside of the Dash framework. I am new to this type of setup and as a result I am starting off simple by recreating the "More About Visualizations" scatter plot found in the getting started guide with the slight addition of also adding a lowess regression. The desired outcome is that the sample graph remains identical with the fitted regression added. The code I have is:
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
import statsmodels.api as sm
app = dash.Dash()
df = pd.read_csv(
'https://gist.githubusercontent.com/chriddyp/' +
'5d1ea79569ed194d432e56108a04d188/raw/' +
'a9f9e8076b837d541398e999dcbac2b2826a81f8/'+
'gdp-life-exp-2007.csv')
performance_line = pd.DataFrame(sm.nonparametric.lowess(df['life expectancy'], df['gdp per capita'], frac=0.75))
app.layout = html.Div([
dcc.Graph(
id='life-exp-vs-gdp',
figure={
'data': [
go.Scatter(
x = performance_line[0],
y = performance_line[1],
mode = 'lines',
line = dict(
width=0.5
),
name = 'Fit'
),
go.Scatter(
x=df[df['continent'] == i]['gdp per capita'],
y=df[df['continent'] == i]['life expectancy'],
text=df[df['continent'] == i]['country'],
mode='markers',
opacity=0.7,
marker={
'size': 15,
'line': {'width': 0.5, 'color': 'white'}
},
name=i
) for i in df.continent.unique()
],
'layout': go.Layout(
xaxis={'type': 'log', 'title': 'GDP Per Capita'},
yaxis={'title': 'Life Expectancy'},
margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
legend={'x': 0, 'y': 1},
hovermode='closest'
)
}
)
])
if __name__ == '__main__':
app.run_server()
This code will not work because of the for loop after the scatter plot. I have tried encompassing it in () and [], but the JSON subroutine cannot handle generators and the [] stops the breaking but does not actually plot the scatter plot. How can i get this graph with the additional lowess regression?
It seems to me like a syntax problem, list comprehensions have the following format (forgive the simplicity):
[(something with i) for i in (iterable)]
while what you're trying looks like
[(unrelated item), (something with i) for i in (iterable)]
The following slight modification should work:
[(unrelated item)]+[(something with i) for i in (iterable)]
so the final code will be something like this.
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
import pandas as pd
import statsmodels.api as sm
app = dash.Dash()
df = pd.read_csv(
'https://gist.githubusercontent.com/chriddyp/' +
'5d1ea79569ed194d432e56108a04d188/raw/' +
'a9f9e8076b837d541398e999dcbac2b2826a81f8/'+
'gdp-life-exp-2007.csv')
performance_line = pd.DataFrame(sm.nonparametric.lowess(df['life expectancy'], df['gdp per capita'], frac=0.75))
app.layout = html.Div([
dcc.Graph(
id='life-exp-vs-gdp',
figure={
'data': [
go.Scatter(
x = performance_line[0],
y = performance_line[1],
mode = 'lines',
line = dict(
width=0.5
),
name = 'Fit'
)
]+[
go.Scatter(
x=df[df['continent'] == i]['gdp per capita'],
y=df[df['continent'] == i]['life expectancy'],
text=df[df['continent'] == i]['country'],
mode='markers',
opacity=0.7,
marker={
'size': 15,
'line': {'width': 0.5, 'color': 'white'}
},
name=i
) for i in df.continent.unique()
],
'layout': go.Layout(
xaxis={'type': 'log', 'title': 'GDP Per Capita'},
yaxis={'title': 'Life Expectancy'},
margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
legend={'x': 0, 'y': 1},
hovermode='closest'
)
}
)
])
if __name__ == '__main__':
app.run_server()

Categories