Error updating graph invalid component prop figure - python

Just creating a simple Graph, from an excel file, it loads correctly but at the moment of updating the graph dash gives back this error:
Failed component prop type: Invalid component prop figure key props supplied to Graph.
Bad object: {
“props”: {
“id”: “average_country”,
“figure”: {
“data”: [
{
“x”: [
“DE”,
“ES”,
“FR”,
“IT”,
“UK”
],
“y”: [
[
2365.56,
4528.33875,
4851.085,
4325.14,
2107.921428571429
]
],
“type”: “bar”
}
],
“layout”: {
“title”: “Hyperzone”
}
}
},
“type”: “Graph”,
“namespace”: “dash_core_components”
}
Valid keys: [
“data”,
“layout”,
“frames”
]
I’m just using a pivot table to create the mean of data of some countries, here’s my code, the pivot table is correct and outputs a valid result with the values I want, just when I try to update the graph with the callback function it returns an Error message.
import pandas as pd
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from dash.dependencies import Input, Output
HP= pd.read_excel(r’C:\Users\salinejs\HP.xlsx’)
Columns = [‘Station’, ‘Week’, ‘Owner’, ‘Cost’,‘Country’]
HP_filtered = HP[Columns]
avaliable_weeks= HP_filtered[‘Week’].unique()
external_stylesheets = [‘https://codepen.io/chriddyp/pen/bWLwgP.css’]
app = dash.Dash(name, external_stylesheets=external_stylesheets)
app.layout = html.Div([
html.Div([
html.Div([
html.Div([
dcc.Dropdown(
id= 'Week_filter',
options = [{'label':j, 'value':j}for j in avaliable_weeks],
value= 'Week 42'
),
],
style= {'float':'left', 'display':'inline-block'}
),
html.Div([
dcc.Graph(
id='average_country',
)
],
)
]
),
],
)
#app.callback(
Output(‘average_country’, ‘figure’),
[Input(‘Week_filter’,‘value’)]
)
def update_value(week):
HP_filtered_week = HP_filtered[ HP_filtered['Week'] == week ]
pv = pd.pivot_table(HP_filtered_week, values='Cost', columns='Country', index='Week')
print(pv)
print(pv.columns)
return dcc.Graph(
id='average_country',
figure={
'data': [{'x': pv.columns , 'y' : pv.values,'type': 'bar'
}],
'layout':{
'title': 'Cost',
}
})
if name == ‘main’:
app.run_server(debug=True)

A bit late - you probably sorted this by now, but I just had the same error and an answer here would have saved me time.
It's because you are sending the callback output to figure but the function is returning the entire dcc.Graph() instead of just the figure.
change
return dcc.Graph(
id='average_country',
figure={
'data': [{'x': pv.columns , 'y' : pv.values,'type': 'bar'
}],
'layout':{
'title': 'Cost',
}
})
to
return {'data': [{'x': pv.columns , 'y' : pv.values,'type': 'bar'
}],
'layout':{
'title': 'Cost',},}

Related

Plotly Dash Update Drop Down from call back where data frame inside the call back

I am trying to update the drop-down menu from the data frame column value where my data frame is generated inside call back since I am taking user inputs and extracting some data from API.
I want to create a filter in the dropdown that's why I want that drop-down updated dynamically using the data frame column.
so in a call back I have df['name_id'] through which I want to update the segment dropdown.
I have taken the only important line to break in my code since the code is too lengthy:
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import datetime
import dash_table
import httplib2
import pandas as pd
import requests
import io
import time
from Dash_App.app import app
from dash.dependencies import Input, Output, State
from oauth2client import GOOGLE_REVOKE_URI, GOOGLE_TOKEN_URI, client
from oauth2client import client, GOOGLE_TOKEN_URI
from datetime import date, timedelta
from apiclient import discovery
row1 = html.Div(
[
dbc.Row([
dbc.Col([
dbc.Input(id="client_id",
type="text",
placeholder="Client ID",
style={'width': '150px'}, persistence=True,
persistence_type='memory'),
]),
], align="center"),
], style={'margin-top': 20, 'margin-left': -90}
)
row2 = html.Div([
dbc.Row([
dbc.Col([
dcc.Dropdown(
id='segment',
options=[{'label': i, 'value': i} for i in "what"],
multi=True,
style={'width': '250px'},
placeholder='Segment'),
]),
])
])
tab_2_layout = dbc.Container(children=[
row1,
html.Br(),
row2,
]
)
#app.callback(Output('output_div-ga', 'children'),
[Input('submit-button', 'n_clicks')],
[State('client_id', 'value'),
],
)
def ga_output(clicks, client_id):
if clicks is not None:
my_client_id = client_id
credentials = client.OAuth2Credentials(
access_token=None, # set access_token to None since we use a refresh token
client_id=my_client_id)
credentials.refresh(httplib2.Http()) # refresh the access token (optional)
http = credentials.authorize(httplib2.Http()) # apply the credentials
service_v3 = discovery.build('analytics', 'v3', http=http)
segments = service_v3.management().segments().list().execute()
df = pd.DataFrame(segments['items'])
df = df[['name', 'id']]
df['name_id'] = df.name.astype(str).str.cat(df.id.astype(str), sep=':')
return html.Div([dcc.Store('memory'),
dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in dff.columns],
data=dff.to_dict("rows"), persistence=True, persistence_type='memory',
export_format="csv",
),
])
I am able to solve this by generating form inside call back.
return html.Div([
dbc.Row([
dbc.Col([
dcc.Dropdown(
id='segment',
options=[{'label': i, 'value': i} for i in df['name_id'].unique()],
persistence=True, persistence_type='memory',
multi=True,
style={'width': '250px', 'margin-left': -250, 'margin-top': 10},
placeholder='Segment'),
]), ]), ])
What worked for me was to give each column that you want to edit an id, make it editable and then update the dropdown options in the DataTable. I also returned the whole DataTable in my callback.
app.callback(
Output("table-dropdown-container", "children"),
Input("input-data-table-id", "data"),
)(self.update_unlabelled_shops_table)
...
dt = (
dash_table.DataTable(
id='table-id',
data=df.to_dict("records"),
columns=[{"name": i, "id": i} if i != column_name else {"name": i, "id": i, "editable": True, "presentation": "dropdown"} for i in df.columns],
page_size=8,
dropdown={
column_name: {
"options": [
{"label": i, "value": i}
for i in df[column_name].unique()
]
},
},
),
)
return dt
except Exception as e:
print(e)
return [None]
And to create your div block.
def create_div(self):
return html.Div(
[
dash_table.DataTable(
id='table-id',
columns=[],
editable=True,
dropdown={},
),
html.Div(id="table-dropdown-container"),
]
)
Hope this helps somebody...

Export Plotly Dash datatable output to a CSV by clicking download link

Hi Anyone able to help advise?
I have an issue trying to export the data being populated from data table filtered from drop down selection upon clicking on download link to a CSV file.
Error gotten after clicking on the Download Link
csv_string = dff.to_csv(index=False, encoding='utf-8')
AttributeError: 'str' object has no attribute 'to_csv'
And the file that was downloaded is a file containing html code.
Code snippets below
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output,State
import plotly.graph_objs as go
import dash_table
import dash_table_experiments as dt
from urllib.parse import quote
import flask
import pandas as pd
import numpy as np
import pyodbc
app.layout = html.Div([
html.H3("Sales Summary Report"),
dcc.Graph(
figure={
"data": [
{
"x": df["Sales_RANGE"],
"y": df['count'],
"name":'No of Cust',
"type": "bar",
"marker":{'color':'rgba(26, 118, 255, 0.5)',
#'line':{
# 'color':'rgb(8,48,107)',
# 'width':1.5,
# }
}
}
],
"layout": {
"xaxis": {"automargin": True},
"yaxis": {
"automargin": True,
# "title": {"text": column}
},
"height": 250,
"margin": {"t": 10, "l": 10, "r": 10},
},
},
)
,
html.Label(["Select Sales range to view",
dcc.Dropdown(
id="SalesRange",
style={'height': '30px', 'width': '55%'},
options=[{'label': i,
'value': i
} for i in Sales_Range_Options],
value='All'
)
]),
#TABLE
html.H5("Details"),
html.Div(id='detailsresults') ,
html.A('Download Data',
id='download-link',
download="rawdata.csv",
href="",
target="_blank"
)
])
def generate_table(dataframe):
'''Given dataframe, return template generated using Dash components
'''
return html.Div( [dash_table.DataTable(
#id='match-results',
data=dataframe.to_dict('records'),
columns=[{"name": i, "id": i} for i in dataframe.columns],
editable=False
),
html.Hr()
])
#app.callback(
Output('detailsresults', 'children'),
[
Input('SalesRange', 'value'),
]
)
def load_results(SalesRange):
if SalesRange== 'All':
return generate_table(df)
else:
results = df[df['SALES_RANGE'] == SalesRange]
return generate_table(results)
#app.callback(
dash.dependencies.Output('download-link', 'href'),
[dash.dependencies.Input('SalesRange', 'value')])
def update_download_link(SalesRange):
dff = load_results(SalesRange)
csv_string = dff.to_csv(index=False, encoding='utf-8')
csv_string = "data:text/csv;charset=utf-8,%EF%BB%BF" + quote(csv_string)
return csv_string
CSV export is officially supported by dash_table.DataTable. You simply need to specify export_format='csv' when you build the table:
dash_table.DataTable(
id="table",
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict("records"),
export_format="csv",
)
Here's a complete example app.py that you can run:
import dash
import dash_table
import dash_html_components as html
import pandas as pd
df = pd.DataFrame(
[
["California", 289, 4395, 15.3, 10826],
["Arizona", 48, 1078, 22.5, 2550],
["Nevada", 11, 238, 21.6, 557],
["New Mexico", 33, 261, 7.9, 590],
["Colorado", 20, 118, 5.9, 235],
],
columns=["State", "# Solar Plants", "MW", "Mean MW/Plant", "GWh"],
)
app = dash.Dash(__name__)
server = app.server
app.layout = dash_table.DataTable(
id="table",
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict("records"),
export_format="csv",
)
if __name__ == "__main__":
app.run_server(debug=True)
You will see a button above the table:
I believe your answer is like the following:
#app.server.route('/dash/urlToDownload')
def download_csv():
return send_file('output/downloadFile.csv',
mimetype='text/csv',
attachment_filename='downloadFile.csv',
as_attachment=True)
You may take a look at this link for more information:
Allowing users to download CSV on click

Changing from scattermapbox to densitymapbox causes error

I was looking for a solution to this issue I encountered. There is a question almost similar to mine in plotly community (https://community.plot.ly/t/problem-with-densitymapbox-chart-type/28517), but still haven’t found a resolution. My dropdown menu consists of scattermapbox and densitymapbox as i wanted to juggle between these. However, when changing from scattermapbox to densitymapbox, it results to the image below:
densitymapbox after scattermapbox format
import dash
import copy
import pathlib
import dash
import numpy as np
import math
import datetime as dt
import pandas as pd
from dash.dependencies import Input, Output, State, ClientsideFunction
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import plotly.graph_objs as go
# get relative data folder
PATH = pathlib.Path(__file__).parent
DATA_PATH = PATH.joinpath("data").resolve()
external_scripts = [
‘https://cdn.plot.ly/plotly-1.39.1.min.js’
]
external_stylesheets = [
‘https://codepen.io/etpinard/pen/wxwPXJ’
]
app = dash.Dash(
__name__,
external_scripts=external_scripts,
external_stylesheets=external_stylesheets
)
server = app.server
# Load data
df = pd.read_excel("Clean_TR(6.8.19).xlsx")
group_name = df['gname'].unique()
mapbox_access_token = <your token>
app.layout = html.Div(
[
dcc.Store(id = 'aggregate_data'),
dcc.Dropdown(
id = 'map_plot',
options = [{'label':i, "value":i} for i in ['Scatter', 'Density']],
value = ['Scatter']
),
dcc.Graph(id = 'mindanao-map')
]
)
#app.callback(
Output('mindanao-map', 'figure'),
[Input('map_plot', 'value')]
)
def update_map(map_plot):
if map_plot == "Density":
maptype = 'densitymapbox'
else:
maptype = 'scattermapbox'
return {
'data' : [{
'lat':df['latitude'],
'lon':df['longitude'],
'marker':{
'color': df['freq'],
'size': 8,
'opacity': 0.6
},
'customdata': df['idno'],
'type': maptype
}],
'layout': {
'mapbox': {
'accesstoken': mapbox_access_token,
'style':"light",
'center': dict(lon=123.30, lat= 7.50),
'zoom':'6',
},
'hovermode': 'closest',
'margin': {'l': 0, 'r': 0, 'b': 0, 't': 0}
}
}
if __name__ == "__main__":
app.run_server(debug=True)
But whenever I swap out the if-else ordering, i.e,
if map_plot == "Scatter":
maptype = 'scattermapbox'
else:
maptype = 'densitymapbox'
it results to density map showing, but scatter will not.
Do I need to separate these two instead of if-else? Any inputs will do. Thank you for your time!
This is a Plotly.js bug, and I've filed a report here: https://github.com/plotly/plotly.js/issues/4285
Edit: this bug is fixed in recent versions of Plotly.js and Plotly.py and Dash.

Dash - Dynamic layout does not propagate resized graph dimensions until window is resized

In the sample Dash application below, I am attempting to create a dynamic layout with a variable number of rows and columns. This dynamic grid-style layout will be populated with various graphs that can be modified by dropdowns, etc.
The main issue I have run into thus far pertains to viewport-units and attempting to style the individual graphs appropriately to accommodate the dynamic layout. For example, I am modifying the style of the dcc.Graph() components via viewport-units, where the dimensions (e.g. height and width may be either 35vw or 23vw depending on the number of columns). When I change the number of columns from 3 to 2, for example, the height and width of the dcc.Graph() component are clearly changed, however this change is not reflected in the actual rendered layout until the window is physically resized (see the images below the sample code).
How do I force the dcc.Graph() components to propagate these changes without having to resize the window?
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config.suppress_callback_exceptions = True
app.layout = html.Div([
html.Div(className='row', children=[
html.Div(className='two columns', style={'margin-top': '2%'}, children=[
html.Div(className='row', style={'margin-top': 30}, children=[
html.Div(className='six columns', children=[
html.H6('Rows'),
dcc.Dropdown(
id='rows',
options=[{
'label': i,
'value': i
} for i in [1,2,3,4]],
placeholder='Select number of rows...',
clearable=False,
value=2
),
]),
html.Div(className='six columns', children=[
html.H6('Columns'),
dcc.Dropdown(
id='columns',
options=[{
'label': i,
'value': i
} for i in [1,2,3]],
placeholder='Select number of columns...',
clearable=False,
value=3
),
])
]),
]),
html.Div(className='ten columns', id='layout-div', style={'border-style': 'solid', 'border-color': 'gray'}, children=[])
])
])
#app.callback(
Output('layout-div', 'children'),
[Input('rows', 'value'),
Input('columns', 'value')])
def configure_layout(rows, cols):
mapping = {1: 'twelve columns', 2: 'six columns', 3: 'four columns', 4: 'three columns'}
sizing = {1: '40vw', 2: '35vw', 3: '23vw'}
layout = [html.Div(className='row', children=[
html.Div(className=mapping[cols], children=[
dcc.Graph(
id='test{}'.format(i+1+j*cols),
config={'displayModeBar': False},
style={'width': sizing[cols], 'height': sizing[cols]}
),
]) for i in range(cols)
]) for j in range(rows)]
return layout
#Max layout is 3 X 4
for k in range(1,13):
#app.callback(
[Output('test{}'.format(k), 'figure'),
Output('test{}'.format(k), 'style')],
[Input('columns', 'value')])
def create_graph(cols):
sizing = {1: '40vw', 2: '35vw', 3: '23vw'}
style = {
'width': sizing[cols],
'height': sizing[cols],
}
fig = {'data': [], 'layout': {}}
return [fig, style]
if __name__ == '__main__':
app.server.run()
Relevant screenshots (Image 1 - page load, Image 2 - change columns to 2):
Here is how to proceed:
app.py must import:
from dash.dependencies import Input, Output, State, ClientsideFunction
let’s include the below Div somewhere in the Dash layout:
html.Div(id="output-clientside"),
asset folder must include either your own script, or the default script resizing_script.js, which contains:
if (!window.dash_clientside) {
window.dash_clientside = {};
}
window.dash_clientside.clientside = {
resize: function(value) {
console.log("resizing..."); // for testing
setTimeout(function() {
window.dispatchEvent(new Event("resize"));
console.log("fired resize");
}, 500);
return null;
},
};
Among your callbacks, put this one, without #:
app.clientside_callback(
ClientsideFunction(namespace="clientside", function_name="resize"),
Output("output-clientside", "children"),
[Input("yourGraph_ID", "figure")],
)
At this point, when you manually resize the window, in your browser, the resize function is triggered.
We aim to achieve the same result, but without manual window resizing. For instance, the trigger could be a className update.
So, we apply the following changes:
Step 1: unchanged
Step 2: unchanged
Step 3: let’s add a “resize2” function inside our javascript file, which takes 2 arguments:
if (!window.dash_clientside) {
window.dash_clientside = {};
}
window.dash_clientside.clientside = {
resize: function(value) {
console.log("resizing..."); // for testing
setTimeout(function() {
window.dispatchEvent(new Event("resize"));
console.log("fired resize");
}, 500);
return null;
},
resize2: function(value1, value2) {
console.log("resizingV2..."); // for testing
setTimeout(function() {
window.dispatchEvent(new Event("resize"));
console.log("fired resizeV2");
}, 500);
return value2; // for testing
}
};
Function “resize2” now takes 2 arguments, one for each Input defined in the below callback. It will return the value of “value2” in the Output, specified in this very same callback. You can set it back to “null”, it’s just to illustrate.
Step4: our callback now becomes:
app.clientside_callback(
ClientsideFunction(namespace="clientside", function_name="resize2"),
Output("output-clientside", "children"),
[Input("yourGraph_ID", "figure"), Input("yourDivContainingYourGraph_ID", "className")],
)
Finally, you need a button to trigger the event which will change the className of your container.
let’s say your have:
daq.ToggleSwitch(
id='switchClassName',
label={
'label':['Option1', 'Option2'],
},
value=False,
),
And the following callback:
#app.callback(Output("yourDivContainingYourGraph_ID", "className"),
[Input("switchClassName","value")]
)
def updateClassName(value):
if value==False:
return "twelve columns"
else:
return "nine columns"
Now, if you save everything, refresh, everytime you press on your toggleSwitch,it resizes the container, triggers the function, and refreshes the figure.
Given the way it’s done, I assume it must also be possible to run more Javascript functions, the same way, but I didnt check yet.
Hope it will help some
The behavior looks like a Plotly bug to me.
Here is a possible workaround/short-termin solution.
There is a nice library visdcc which allows callbacks with Javascript. You can install it via
pip install visdcc
Add it to your div:
visdcc.Run_js(id='javascript'),
and add a callback
#app.callback(
Output('javascript', 'run'),
[Input('rows', 'value'),
Input('columns', 'value')])
def resize(_, __):
return "console.log('resize'); window.dispatchEvent(new Event('resize'));"
Plotly will throw an error in the console after the resize event (this also happens when the windows is manually resized) but the plots are shown correctly.
Full code
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import visdcc
SIZING = {1: '40vw', 2: '35vw', 3: '23vw'}
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config.suppress_callback_exceptions = True
app.layout = html.Div([
visdcc.Run_js(id='javascript'),
html.Div(className='row', children=[
html.Div(className='two columns', style={'margin-top': '2%'}, children=[
html.Div(className='row', style={'margin-top': 30}, children=[
html.Div(className='six columns', children=[
html.H6('Rows'),
dcc.Dropdown(
id='rows',
options=[{
'label': i,
'value': i
} for i in [1,2,3,4]],
placeholder='Select number of rows...',
clearable=False,
value=2
),
]),
html.Div(className='six columns', children=[
html.H6('Columns'),
dcc.Dropdown(
id='columns',
options=[{
'label': i,
'value': i
} for i in [1,2,3]],
placeholder='Select number of columns...',
clearable=False,
value=3
),
])
]),
]),
html.Div(className='ten columns', id='layout-div', style={'border-style': 'solid', 'border-color': 'gray'}, children=[])
])
])
#app.callback(
Output('layout-div', 'children'),
[Input('rows', 'value'),
Input('columns', 'value')])
def configure_layout(rows, cols):
mapping = {1: 'twelve columns', 2: 'six columns', 3: 'four columns', 4: 'three columns'}
layout = [html.Div(className='row', children=[
html.Div(className=mapping[cols], style={'width': SIZING[cols], 'height': SIZING[cols]}, children=[
dcc.Graph(
id='test{}'.format(i+1+j*cols),
config={'displayModeBar': False},
style={'width': SIZING[cols], 'height': SIZING[cols]}
),
]) for i in range(cols)
]) for j in range(rows)]
return layout
#app.callback(
Output('javascript', 'run'),
[Input('rows', 'value'),
Input('columns', 'value')])
def resize(_, __):
return "console.log('resize'); window.dispatchEvent(new Event('resize'));"
#Max layout is 3 X 4
for k in range(1,13):
#app.callback(
[Output('test{}'.format(k), 'figure'),
Output('test{}'.format(k), 'style')],
[Input('columns', 'value')])
def create_graph(cols):
style = {
'width': SIZING[cols],
'height': SIZING[cols],
}
fig = {'data': [], 'layout': {}}
return [fig, style]
if __name__ == '__main__':
app.server.run()

Plotly figure hide and display

I have a problem with hiding and showing a graph in the Python framework, Dash.
I define a new graph:
html.Div([
dcc.Graph(id = 'graph'),
],),
After I update my trace data with a callback function I return it and it is shown in the graph, but if nothing is selected from my dropdown menu I do
if not input or input == []:
return {'display': 'none'}
so that my graph is not shown, but it doesn't work for some reason.
Is there a workaround?
Thank you in advance
You can set the id element for the Div holding your graph and hide the whole div by using #app.callback on the style element.
html.Div(id="graph-container", children= [
dcc.Graph(id = 'graph'),
]),
#app.callback(Output('graph-container', 'style'), [Input('input_widget','value')])
def hide_graph(input):
if input:
return {'display':'block'}
else:
return {'display':'none'}
To see this code in action you can test out my code:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
app = dash.Dash()
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
html.Div(children='''
Dash: A web application framework for Python.
'''),
html.Label("Show?"),
dcc.Dropdown(
id="my-input",
options = [
{'label':'Yes', 'value':True},
{'label':'No', 'value':False}
],
value = True
),
html.Div(
id="graph-container",
children = [
dcc.Graph(
id='example-graph',
figure={
'data': [
{'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
{'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
],
'layout': {
'title': 'Dash Data Visualization'
}
}
)
])
])
#app.callback(Output('graph-container', 'style'), [Input('my-input', 'value')])
def hide_graph(my_input):
if my_input:
return {'display':'block'}
return {'display':'none'}
if __name__ == '__main__':
app.run_server(port=8125, debug = True)
Note I used the following versions:
python 3.6.4
dash 0.21.0
dcc 0.22.1
html 0.10.0
Thanks lwileczek for the answer. I wanted to provide an update as the code needs a few minor tweaks to work in the following environment:
python 3.7.4
plotly 4.1.1
dash 1.2.0
dcc 1.1.2
html 1.0.1
When I copied lwileczek's code into the above environment, dash through an error about passing a bad argument into the dropdown. After a couple of moments of trial and error, I was able to make the code work if I changed the values in the dropdown to strings and modified the conditional in the callback so that it was doing a string comparison as opposed to expecting the value to be a boolean.
The code for the dropdown looks like:
dcc.Dropdown(
id = 'my-input',
options = [
{'label':'Yes', 'value':'Yes'},
{'label':'No', 'value':'No'}
],
value='Yes'
),
The code for the conditional in the callback becomes:
if my_input == 'Yes':
return {'display': 'block'}
return {'display': 'none'}
(This should probably be a comment, but I don't have enough points to post a comment)

Categories