If I place dcc.Graph elements hardcoded in the layout:
app.layout = html.Div(
html.Div([
dcc.Graph(id='graph-hammer'),
dcc.Graph(id='graph-saw'),
dcc.Interval(id='interval-component', interval=1000, n_intervals=0)]))
I get my desired result of 2 graphs plotted without problems.
But if I create a list of dcc.Graph elements using append:
list_graphs = []
for t in tools:
list_graphs.append(html.Div(dcc.Graph(id='graph-' + t)))
app.layout = html.Div(
html.Div([
list_graphs,
dcc.Interval(id='interval-component', interval=1000, n_intervals=0)]))
I get a blank screen, with no errors being thrown.
What am I doing wrong when passing the list to the layout?
The solution to this is to add * in front of the list. For example:
app.layout = html.Div(
html.Div([
*list_graphs,
dcc.Interval(id='interval-component', interval=1000, n_intervals=0)]))
Related
In Plotly Dash, you construct a dashboard using HTML or HTML-like components. Now there are many more parameters that can be assigned to "Core" or HTML components, many of which may be commonly shared among components. What I'm trying to figure out is how to store common parameters in a data structure, and deploy that to a variety of components. This would either before cleaning up and streamlining verbose parameters into a short and tidy variable name, or tie parameters to one commonly set point for easier modification. An example:
You can change the persistence of data on refresh or browser close with persistence = True, persistence_type ='memory' in the component declaration. Expanding the snippet above:
from dash import Dash, dcc, html
app = Dash(__name__)
app.layout = html.Div([
dcc.Checklist(
['New York City', 'Montréal', 'San Francisco'],
['Montréal', 'San Francisco'],
inline=True,
persistence = True,
persistence_type = 'memory'
)
dcc.Checklist(
['Steakhouse', 'Seafood', 'Italian'],
['Steakhouse'],
inline=True,
persistence = True,
persistence_type = 'memory'
)
])
if __name__ == '__main__':
app.run_server(debug=True)
What I would like to do is store these parameters as a data structure and assign them to the component dynamically.
from dash import Dash, dcc, html
persist = {'persistence':True, 'persistenceType':'memory'}
app = Dash(__name__)
app.layout = html.Div([
dcc.Checklist(
['New York City', 'Montréal', 'San Francisco'],
['Montréal', 'San Francisco'],
inline=True,
persist
)
dcc.Checklist(
['Steakhouse', 'Seafood', 'Italian'],
['Steakhouse'],
inline=True,
persist
)
])
if __name__ == '__main__':
app.run_server(debug=True)
For this specific example, I know I can have the values True and memory set in a variable, and using that var in the parameter value, but this is just one example and I have some more verbose and challenging situations where I would like to have both the parameter and parameter value stored in a data structure. Is there any way I can achieve that?
You can use the **kwargs syntax to expand/unpack keyword arguments given a dictionary of parameters, for example :
persist = {'persistence': True, 'persistence_type': 'memory'}
app.layout = html.Div([
dcc.Checklist(
['New York City', 'Montréal', 'San Francisco'],
['Montréal', 'San Francisco'],
inline=True,
**persist
)
dcc.Checklist(
['Steakhouse', 'Seafood', 'Italian'],
['Steakhouse'],
inline=True,
**persist
)
])
#see Unpacking With the Asterisk Operators
In the dash application, I have a map displayed with the center in my position and on it I have a point (mark) in the center again as my position. However, I need to dynamically change my position on the map.
The map itself changes its center without problems, but the point (marker) does not, as if it is anchored in its original position and does not move to a new position (the new center of the map).
Here is a simple code that shows it nicely. After running it, the map is redrawn every 2 seconds as I want. But the point remains in the last-origial position..... Does anyone know what I'm doing wrong?
import random
import dash
from dash import dcc,html
from dash.dependencies import Input, Output
import plotly.graph_objects as go
def get_fig():
# random position as center
lat = 48.8 + 1/random.randrange(300, 800)
lon = 20.1+ 1/random.randrange(300, 800)
fig = go.Figure()
# blue point - should be in center of map , vhy is not ?
fig.add_trace(
go.Scattermapbox(
lat=[lat],
lon=[lon],
mode="markers",
marker=go.scattermapbox.Marker(size=20),
)
)
# open street map with center at lat:lon
fig.update_layout(
height=552,
width=640,
margin={"r": 2, "t": 2, "b": 2, "l": 2},
autosize=True,
mapbox=dict(style="open-street-map", center=dict(lat=lat, lon=lon), zoom=16),
)
return fig
app = dash.Dash()
#app.callback(
Output("graph", "figure"),
Input("my_interval", "n_intervals"))
def update_bar_chart(dummy):
return get_fig()
app.layout = html.Div([
dcc.Graph(id = "graph"),
dcc.Interval(id="my_interval", interval=2000, n_intervals=0, disabled=False),
])
app.run_server(debug=True, use_reloader=False)
I use python 3.9 , plotly version is 5.11.0 and dash version is 2.7.0
I've tried several different ways, but they all fail in the same way.
I have restaurant name, cusines, lat , long as columns. The map I am trying to show on the html page is not updating as per the filter , It shows all the restaurnats.
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px
app = dash.Dash('app')
df = pd.read_excel('Resturants.XLSX')
app.layout = html.Div([
html.H1('Resturant map by cusine', style={'text-align': 'center'} ),
dcc.Dropdown(id='cusine_dd',
options=[{'label': i, 'value': i} for i in df.cusines.unique()],
value = 'Chinese',
style={'width':'40%'}),
html.Div(id= 'output', children =[] ),
dcc.Graph(id='mapbycusine', figure={})
])
#app.callback(
[Output(component_id='output', component_property='children'),
Output(component_id='mapbycusine', component_property='figure')],
[Input(component_id='cusine_dd', component_property='value')]
)
def update_figure(input_cusine):
#cusine_filter = 'All'
container = f"Currently showing {input_cusine}"
df_copy = df.copy(deep=True)
if input_cusine:
df_copy = df_copy[df_copy['cusines'] == input_cusine]
print(df_copy.head())
fig = px.scatter_mapbox(data_frame=df_copy, lat='Latitude', lon='Longitude', zoom=3, height=300, hover_data= ['cusines'])
fig.update_layout(mapbox_style="open-street-map")
fig.update_layout(height=1000, margin={"r":100,"t":100,"l":100,"b":300})
return container, fig
if __name__ == '__main__':
app.run_server(debug=True)
I am checking every step just to make sure if input and output is working I have used countainers updates on the html page and print the df_copy after filtering data as per the input cusine. The containers give the correct output and the df.copy.head() shows only filltered columns in the console but the map on html dash app is not updating.
I want the map to show the restaurants for just the selected cusine
I cannot reproduce your error, but perhaps some of the steps I took in debugging might prove helpful:
First, I took the first 100 rows of a restaurant dataset from kaggle, and then randomly assigned three different cuisine types to each unique restaurant name. Then when creating the fig object with px.scatter_mapbox, I passed the cuisine column to the color argument and a mapping between cuisine and color to the color_discrete_map argument so that the marker colors will be different when you select different cuisine types from the dropdown.
This is the result, with visible changes between the marker locations as well as the marker colors (depending on the dropdown selection). Also, as you mentioned, the print outs of df_copy from inside your update_figure function match the dropdown selections as expected.
As far as I can tell, the only thing fundamentally different between your dashboard and mine would be the data that was used. Maybe it is possible that you have a bunch of duplicate rows that span multiple cuisines (i.e. imagine I took a data set of only Mexican restaurants, then duplicated all of the rows but switched the cuisine to Italian – then if you select Mexican or Italian from the dropdown, the result would be the same because you're plotting all of the same latitudes and longitudes in each case so the figure wouldn't appear to change, and you might not catch this from examining the df_copy print outs).
Can you verify that your data set doesn't contain duplicate latitude and longitude points with different cuisines assigned to the same point?
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
import numpy as np
import pandas as pd
import plotly.express as px
app = dash.Dash('app')
# df = pd.read_excel('Resturants.XLSX')
## create a small restaurant dataset similar to yours
## downloaded from: https://www.kaggle.com/datasets/khushishahh/fast-food-restaurants-across-us?resource=download
df = pd.read_csv('Fast_Food_Restaurants_US.csv', nrows=100, usecols=['latitude','longitude','name'])
df.rename(columns={'latitude':'Latitude', 'longitude':'Longitude'}, inplace=True)
## randomly assign some cuisine types to unique restaurant names
unique_names = df['name'].unique()
np.random.seed(42)
name_cuisine_map = {
name:cuisine for name,cuisine in
zip(unique_names, np.random.choice(['American','Mexican','Chinese'], size=len(unique_names)))
}
cuisine_color_map = {
'American':'blue',
'Mexican':'green',
'Chinese':'red'
}
df['cusines'] = df['name'].map(name_cuisine_map)
df['color'] = df['cusines'].map(cuisine_color_map)
app.layout = html.Div([
html.H1('Resturant map by cusine', style={'text-align': 'center'} ),
dcc.Dropdown(id='cusine_dd',
options=[{'label': i, 'value': i} for i in df.cusines.unique()],
value = 'Chinese',
style={'width':'40%'}),
html.Div(id= 'output', children =[] ),
dcc.Graph(id='mapbycusine', figure={})
])
#app.callback(
[Output(component_id='output', component_property='children'),
Output(component_id='mapbycusine', component_property='figure')],
[Input(component_id='cusine_dd', component_property='value')]
)
def update_figure(input_cusine):
#cusine_filter = 'All'
container = f"Currently showing {input_cusine}"
df_copy = df.copy(deep=True)
if input_cusine:
df_copy = df_copy[df_copy['cusines'] == input_cusine]
print("\n")
print(df_copy.head())
fig = px.scatter_mapbox(data_frame=df_copy, lat='Latitude', lon='Longitude', zoom=3, height=300, hover_data= ['cusines'], color='cusines', color_discrete_map=cuisine_color_map)
fig.update_layout(mapbox_style="open-street-map")
fig.update_layout(height=1000, margin={"r":100,"t":100,"l":100,"b":300})
return container, fig
if __name__ == '__main__':
app.run_server(debug=True)
I am using the RangeSlider in Python Dash. This slider is supposed to allow users to select a range of dates to display, somewhere between the minimum and maximum years in the dataset. The issue that I am having is that each mark shows as 2k due to it being automatically rounded. The years range between 1784 and 2020, with a step of 10 each time. How do I get the marks to show as the actual dates and not just 2k? This is what I have below.
dcc.RangeSlider(sun['Year'].min(), sun['Year'].max(), 10,
value=[sun['Year'].min(), sun['Year'].max()], id='years')
You can use attribute marks to style the ticks of the sliders as follows:
marks={i: '{}'.format(i) for i in range(1784,2021,10)}
The full code:
from dash import Dash, dcc, html
app = Dash(__name__)
app.layout = html.Div([
dcc.RangeSlider(1784, 2020,
id='non-linear-range-slider',
marks={i: '{}'.format(i) for i in range(1784,2021,10)},
value=list(range(1784,2021,10)),
dots=False,
step=10,
updatemode='drag'
),
html.Div(id='output-container-range-slider-non-linear', style={'margin-top': 20})
])
if __name__ == '__main__':
app.run_server(debug=True, use_reloader=False)
Output
I'm trying to build a dashboard with Dash from Plotly composed of a series of tiles (Text) like in the picture below.
I'm trying to build a component to reuse it an build the layout below. Each box will contain a Title, a value and a description as shown below.
Is there a component available? Can someone help me with any basic idea/code ?
Thanks in advance!
I would recommend checking out Dash Bootstrap Components (dbc).
You can use dbc.Col (columns) components nested into dbc.Row (rows) components to produce your layout. You can check them out here.
Then for the actual 'cards' as I'll call them, you can use the dbc.Card component. Here's the link.
Here's some example code replicating your layout:
import dash_bootstrap_components as dbc
import dash_html_components as html
card = dbc.Card(
dbc.CardBody(
[
html.H4("Title", id="card-title"),
html.H2("100", id="card-value"),
html.P("Description", id="card-description")
]
)
)
layout = html.Div([
dbc.Row([
dbc.Col([card]), dbc.Col([card]), dbc.Col([card]), dbc.Col([card]), dbc.Col([card])
]),
dbc.Row([
dbc.Col([card]), dbc.Col([card]), dbc.Col([card]), dbc.Col([card])
]),
dbc.Row([
dbc.Col([card]), dbc.Col([card])
])
])
Best thing would probably be to have a function which creates those cards with parameters for ids, titles and descriptions to save the hassle of creating different cards:
def create_card(card_id, title, description):
return dbc.Card(
dbc.CardBody(
[
html.H4(title, id=f"{card_id}-title"),
html.H2("100", id=f"{card_id}-value"),
html.P(description, id=f"{card_id}-description")
]
)
)
You can then just replace each card with create_card('id', 'Title', 'Description') as you please.
Another quick tip is that the col component has a parameter, width. You can give each column in a row a different value to adjust the relative widths. You can read more about that in the docs I linked above.
Hope this helps,
Ollie