I'm want to create multiple dbc.Button by passing a list of strings to a constructor that generates these buttons, in the following way:
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import plotly.express as px
from functools import lru_cache
import dash_bootstrap_components as dbc
from dash.dependencies import Input
from dash.dependencies import Output
from dash.dependencies import State
import pandas as pd
data = {'teams': ['team1', 'team2', 'team3', 'team4']}
df_teams = pd.DataFrame(data)
def generate_team_button(team_shortName):
return dbc.Button(
str(team_shortName),
color="primary",
className="mr-1",
id=str(team_shortName),
),
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
colors = {
'background': '#111111',
'text': '#7FDBFF'
}
app.layout = html.Div(
[
dbc.Row([
dbc.Col(
[generate_team_button(i) for i in df_teams.iterrows()]
)
]),
],
)
if __name__ == '__main__':
app.run_server(debug=True)
But I'm getting the following error for all the generated buttons when trying to do above:
The children property of a component is a list of lists,
instead of just a list. Check the component that has the
following contents, and remove one of the levels of nesting:
[
{
"props": {
"children": "(0, 0 team1\nName: 0, dtype: object)",
"id": "(0, 0 team1\nName: 0, dtype: object)",
"className": "mr-1",
"color": "primary"
},
"type": "Button",
"namespace": "dash_bootstrap_components"
}
]
What do I have to do to generate the buttons?
There is a small bug in your code, if you delete the comma after the generate_team_button() function you will not get the error anymore. You may also want to replace df_teams.iterrows() with df_teams['teams'], see the example below.
import dash
import dash_html_components as html
import dash_bootstrap_components as dbc
import pandas as pd
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
data = {'teams': ['team1', 'team2', 'team3', 'team4']}
df_teams = pd.DataFrame(data)
def generate_team_button(team_shortName):
return dbc.Button(children=str(team_shortName),
color="primary",
className="mr-1",
id=str(team_shortName))
app.layout = html.Div([
dbc.Row([
dbc.Col(children=[generate_team_button(i) for i in df_teams['teams']])
])
])
if __name__ == '__main__':
app.run_server(debug=True)
Related
I'm using tabs inside of Plotly Dash application like given below, and it works fine.
import dash
from dash import Dash, dash_table, dcc, html, Input, Output, callback, State
import plotly.express as px
import dash_bootstrap_components as dbc
import pandas as pd
import plotly.graph_objs as go
import plotly.express as px
tabs = html.Div(
[
dbc.Tabs(
[
dbc.Tab(label="Tab 1", tab_id="tab-1"),
dbc.Tab(label="Tab 2", tab_id="tab-2"),
],
id="tabs",
active_tab="tab-1",
),
html.Div(id="content"),
]
)
app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.title = "Financial Report"
server = app.server
app.layout = html.Div(
dbc.Row([
tabs])
)
#app.callback(Output("content", "children"), [Input("tabs", "active_tab")])
def ind2(value):
purchase = {'date': ['11/03/2021', '12/03/2021', '14/03/2021', '11/03/2021'],
'price': [300, 400, 200, 200],
'currency': ['eur', 'usd', 'usd', 'usd'],
'qty': [200, 300, 400, 500],
'salesman': ['AC', 'BC', "CC", 'DC']}
pur = pd.DataFrame(purchase)
fig2 = go.Figure()
for i in pur['currency'].unique():
fig2.add_trace(go.Bar(x=pur['date'], y=pur[pur['currency'] == i]['qty'], name=i))
fig2.update_layout(barmode="group")
if value=='tab-2':
return dbc.Row(
[
dbc.Col(dcc.Graph(id='bargraph',
figure=fig2)),
]
)
else:
return html.P("Welcome...")
if __name__ == "__main__":
app.run_server(debug=True)
But when I'm trying to add this code to the Dash Page which has mutlti pages it doesn't return anything, tabs seem to be inactive.
(https://dash.plotly.com/urls#example-with-different-pages)
to summarize, I want this page as in picture below. but not only side bar working but tabs inside of the page also.
oh, I figured it out, that main problem was #app.callback.
Since we don't have app in the multipage application (I mean in each page, so just #callback should be used).
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
here is code:
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import numpy as np
from jupyter_dash import JupyterDash
import dash_table
app = Dash(__name__)
ALLOWED_TYPES = (
"text", "number", "password", "email", "search",
"tel", "url", "range", "hidden",
)
app.layout = html.Div(
[
dcc.Input(
id="input_{}".format(_),
type=_,
placeholder="input type {}".format(_),
)
for _ in ALLOWED_TYPES
]
+ [html.Div(id="out-all-types")]
)
#app.callback(
Output("out-all-types", "children"),
[Input("input_{}".format(_), "value") for _ in ALLOWED_TYPES],
)
def cb_render(*vals):
return " | ".join((str(val) for val in vals if val))
if __name__ == "__main__":
app.run_server(port=8051)
i try to give input dash but i have error look in this screenshot:
Adding images to dropdown labels as described in paragraph Components as Option Labels in
https://dash.plotly.com/dash-core-components/dropdown
makes labels not searchable even though searchable=True is set.
Is there workaround to make labels searchable as usual?
Minimal working code:
import pandas as pd
import plotly
import plotly.express as px
import json
import dash_bootstrap_components as dbc
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
df = pd.read_csv('data_bdo.csv', index_col=0)
temp=[
{
"label": html.Div(
[
html.Img(src="/assets/1.png", height=20),
html.Div("Python", style={'font-size': 15, 'padding-left': 10}),
], style={'display': 'flex', 'align-items': 'center', 'justify-content': 'center'}
),
"value": "Python",
},
{
"label": html.Div(
[
html.Img(src="/assets/2.png", height=20),
html.Div("Julia", style={'font-size': 15, 'padding-left': 10}),
], style={'display': 'flex', 'align-items': 'center', 'justify-content': 'center'}
),
"value": "Julia",
},]
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.DARKLY],update_title = None )
app.layout = html.Div([
html.Div([
dcc.Dropdown(id='my_dropdown',
options=temp,
searchable=True #allow user-searching of dropdown values
)],className='three columns')])
#app.callback(
Output(component_id='the_graph', component_property='figure'),
[Input(component_id='my_dropdown', component_property='value')]
)
def update_bar_chart(my_dropdown):
df = pd.read_csv('data_bdo.csv', index_col=0)
fig = px.bar(df[["name", my_dropdown]].dropna().sort_values(by=my_dropdown,ascending=False),
x="name",
y=my_dropdown,
template = 'plotly_dark',
text=my_dropdown,
labels={my_dropdown:"Amount of "+ str(my_dropdown)}
)
fig.update_traces(textfont_size=13, textposition="outside", cliponaxis=False)
return fig
if __name__ == '__main__':
app.run_server(debug=True, use_reloader=False)
Dropdown with options of the form [{'label': 'Python', 'value': 'Python'}] is searchable though...
I have the following skeleton code
# ------------------------------
# IMPORT LIBRARIES
# ------------------------------
# Import Dash and Dash Bootstrap Components
import dash
import dash_bootstrap_components as dbc
from dash import Input, Output, dcc, html, dash_table, State
import dash_leaflet as dl
# Import Core Libraries
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from dash import Input, Output, dcc, html, dash_table
token='my_token'
FONT_AWESOME = "https://use.fontawesome.com/releases/v5.10.2/css/all.css"
# Import data
data_url = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vSGcAFoXyMXk7lj3KJrpzKd5XiBufm2xa7M39QNZxw5ma0TZhP35q-mf2ybyf9cZQdEwsoWkHiQWfjC/pub?gid=0&single=true&output=csv'
df = pd.read_csv(data_url)
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP,FONT_AWESOME], title='CONFIRM - SK4U', update_title=None,
meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=0.7, minimum-scale=0.4"}],
)
server = app.server
fig_map = px.scatter_mapbox(df,lat='latitude',lon='longitude',
mapbox_style='mapbox://styles/vostpt/cl1w0k6uf000415nt86nk7uv2',
#color='Kategória / Category',
width=1400,height=700,
hover_name='name',
#center=[48.799330977271445,19.338585158029197],
center=dict(lon=20.0068, lat=48.8264),
zoom=7,
custom_data=['name']
)
fig_map.update_layout(
hoverlabel=dict(
bgcolor="white",
font_size=16,
font_family="sans-serif"
)
)
fig_map.update_layout(mapbox = dict(accesstoken = token, style ='mapbox://styles/vostpt/cl1w0k6uf000415nt86nk7uv2'))
app.layout = html.Div(
[
dbc.Row(
[
dbc.Col(
dbc.Card(
dbc.CardBody(
[
html.H4("Title", className="card-title"),
html.H6("Card subtitle", className="card-subtitle"),
html.P(id="card_data"),
dbc.CardLink("Card link", href="#"),
dbc.CardLink("External link", href="https://google.com"),
]
),
),
),
dbc.Col(
dcc.Graph(id="my_map",figure=fig_map),
xs=12,
),
],
),
],
)
#app.callback(
Output(component_id="card_data", component_property="children"),
Input(component_id="my_map", component_property="hoverData")
)
def upgrade_card(hoverData):
title = hoverData['name'][0]
return title
if __name__ == "__main__":
app.run_server(host='0.0.0.0', debug=True)
My objective is to update the text in the card, with the data from the dataframe, on mouse hover.
The app receives the input from the hoverData but returns the error message
TypeError: 'NoneType' object is not subscriptable
Any help would be much appreciated.
Disclaimer: The solution will be used in a non-for-profit NGO's project. No commercial use will be made of the solution
These errors usually come up when you did not properly initialize. The children of the p-tag are non-existent in your example, so they cannot be updated.
So, replace html.P(id="card_data") with html.P("", id="card_data").
I have a function that dynamically creates a set of buttons:
def generate_team_button(team_shortName):
return dbc.Button(
str(team_shortName),
className="btn btn-primary",
id=str(team_shortName),
style={
"margin-right": "10px",
"margin-bottom": '10px',
},
n_clicks=0,
)
These buttons are displayed by looping through a set of items
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
from dash.dependencies import Input
from dash.dependencies import Output
from dash.dependencies import State
import pandas as pd
data = {'teams': ['team1', 'team2', 'team3', 'team4']}
df_teams = pd.DataFrame(data)
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div(
[
dbc.Row([
dbc.Col(
children=[generate_team_button(i) for i in df_teams['teams']]
),
]),
dbc.Row([
dbc.Col(
id='section',
#WANT TO UPDATE THIS SECTION BASED ON WHICH BUTTON IS BEEING CLICKED
),
]),
]
),
What I want to do is to update id=section based on which button is being pressed. To do that I need a #app.callback like below. But what I get is a tuple with how many times each button has been pressed.
#app.callback(
[
Output('league-table', 'value'),
],
[
Input(str(i), 'n_clicks') for i in df_teams['teams']
]
)
def update_league_table(*args):
print(args)
return f'{args}'
How can I update a section based on which button has been clicked?
This information is available via the callback_context object. Here is a small example,
import dash
import dash_html_components as html
from dash.dependencies import Output, Input
from dash import callback_context
n_buttons = 5
# Create example app.
app = dash.Dash(prevent_initial_callbacks=True)
app.layout = html.Div([html.Button("Button {}".format(i), id=str(i)) for i in range(n_buttons)] + [html.Div(id="log")])
#app.callback(Output("log", "children"), [Input(str(i), "n_clicks") for i in range(n_buttons)])
def func(*args):
trigger = callback_context.triggered[0]
return "You clicked button {}".format(trigger["prop_id"].split(".")[0])
if __name__ == '__main__':
app.run_server()
For additional details, see the documentation on advanced callbacks.