List item
import os
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import keyring
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.io as pio
import seaborn as sns
from dash import dash, dcc, html
from dash.dependencies import Input, Output, State
from dash_bootstrap_templates import load_figure_template
from sqlalchemy.types import NVARCHAR
from HANA_connect import HANA
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.DARKLY])
load_figure_template("darkly")
colors = {
'background': '#111111',
'text': 'white'
}
login = os.getlogin() # Login holen
pwd=keyring.get_password('HANA_CS4',os.getlogin().upper()) # Passwort holen
cs4 = HANA(login, pwd) # Verbindung ertellen
sqlquery="""SELECT * FROM ZOLS2.korr_plot"""
df = cs4.getDf2(sqlquery)
sqlquery="""SELECT * FROM ZOLS2.hccoop_Treemap WHERE CCM_HC_CD IN ('010112') and NU_AP>50000"""
sqlquery="""SELECT * FROM ZOLS2.HCCOOP_TREEMAP_ZEITREIHE WHERE CCM_HC_CD IN ('010112') """
df1 = cs4.getDf2(sqlquery)
df1.head()
df1.JAHR_MONAT.unique()
ap= '202108'
vp= '202208'
df_ap = df1.loc[df1.JAHR_MONAT==ap,['JAHR_MONAT', 'CCM_HC_CD', 'CCM_HC_TEXT', 'CCM_CATEGORY_CD','CCM_CATEGORY_TEXT', 'CCM_SUBCATEGORY_CD', 'CCM_SUBCATEGORY_TEXT','MARKE_CD', 'MARKE_TEXT', 'NU','DB_KUNDE']]
df_vp = df1.loc[df1.JAHR_MONAT==vp,['JAHR_MONAT', 'CCM_HC_CD', 'CCM_HC_TEXT', 'CCM_CATEGORY_CD','CCM_CATEGORY_TEXT', 'CCM_SUBCATEGORY_CD', 'CCM_SUBCATEGORY_TEXT','MARKE_CD', 'MARKE_TEXT', 'NU','DB_KUNDE']]
df_tree = pd.merge(df_ap, df_vp, how='inner', on = [ 'CCM_HC_CD', 'CCM_HC_TEXT', 'CCM_CATEGORY_CD','CCM_CATEGORY_TEXT', 'CCM_SUBCATEGORY_CD', 'CCM_SUBCATEGORY_TEXT','MARKE_CD', 'MARKE_TEXT'],suffixes=('_AP', '_VP'))
df_tree['NU_INDEX'] = df_tree.NU_AP/df_tree.NU_VP
df_tree['DB_INDEX'] = df_tree.DB_KUNDE_AP/df_tree.DB_KUNDE_VP
df_tree['NU_INDEX'] = df_tree['NU_INDEX'].apply(lambda x : 1 if x==0 else x)
df_tree['NU_INDEX'] = df_tree['NU_INDEX'].astype(float)
df_tree['NU_INDEX'] = round(df_tree['NU_INDEX']*1,4)
df_tree['DB_INDEX'] = df_tree['DB_INDEX'].apply(lambda x : 1 if x==0 else x)
df_tree['DB_INDEX'] = df_tree['DB_INDEX'].astype(float)
df_tree['DB_INDEX'] = round(df_tree['DB_INDEX']*1,4)
df_tree.NU_VP = df_tree.NU_VP.astype(float)
df_tree.NU_AP = df_tree.NU_AP.astype(float)
df_tree.DB_KUNDE_VP = df_tree.DB_KUNDE_VP.astype(float)
df_tree.DB_KUNDE_AP = df_tree.DB_KUNDE_AP.astype(float)
df_tree.CCM_HC_TEXT = df_tree.CCM_HC_TEXT.astype(str)
df_tree.CCM_CATEGORY_TEXT = df_tree.CCM_CATEGORY_TEXT.astype(str)
df_tree.CCM_SUBCATEGORY_TEXT = df_tree.CCM_SUBCATEGORY_TEXT.astype(str)
df_tree.MARKE_TEXT = df_tree.MARKE_TEXT.astype(str)
#df1.CCM_SEGMENT_TEXT = df1.CCM_SEGMENT_TEXT.astype(str)
#df1.CCM_SUBSEGMENT_TEXT = df1.CCM_SUBSEGMENT_TEXT.astype(str)
df_tree.fillna('-', inplace=True)
df_tree = df_tree[df_tree['NU_AP']!=0]
df_tree['INDEX_COLOR_NU'] = df_tree['NU_INDEX'].apply(lambda x : 0.6 if x<0.6 else 1.4 if x>1.4 else x)
df_tree['INDEX_COLOR_DB'] = df_tree['DB_INDEX'].apply(lambda x : 0.6 if x<0.6 else 1.4 if x>1.4 else x)
fig = px.treemap(df_tree, path=[px.Constant("Coop"),"CCM_HC_TEXT" ,"CCM_CATEGORY_TEXT","CCM_SUBCATEGORY_TEXT",'MARKE_TEXT'], values='NU_AP',
color_continuous_scale=[(0, "red"), (0.5, "white"), (1, "green")],
color_continuous_midpoint=1,
color=df_tree.INDEX_COLOR_NU,
width=3840, height=1750)
fig.update_layout(margin = dict(t=100, l=50, r=25, b=25))
app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[
html.H1(
children='Brot/Backwaren NU Dashboard',
style={
'textAlign': 'center',
'color': colors['text']
}
),
dcc.Dropdown([{
"label": html.Div(['08.2022'], style={'text': 'black', 'font-size': 20}),
"value": "202208",
},
{
"label": html.Div(['07.2022'], style={'text': 'black', 'font-size': 20}),
"value": "202207",
},
{
"label": html.Div(['06.2022'], style={'text': 'black', 'font-size': 20}),
"value": "202206",
}, ], value='202208', id='demo1dropdown'),
html.Div(id='dd1outputcontainer'),
dcc.Dropdown([{
"label": html.Div(['08.2022'], style={'text': 'black', 'font-size': 20}),
"value": "202208",
},
{
"label": html.Div(['07.2022'], style={'text': 'black', 'font-size': 20}),
"value": "202207",
},
{
"label": html.Div(['06.2021'], style={'text': 'black', 'font-size': 20}),
"value": "202106",
}, ], placeholder='Select_Datum', value='202208',
id='demo2dropdown'),
html.Div(id='dd2outputcontainer'),
dcc.Graph(
id='life-exp-vs-gdp',
figure = fig
)
])
#app.callback(
Output('dd2outputcontainer', 'children'),
Input('demo2dropdown', 'value'))
def update_figure(selected_date):
filtered_df = df_ap[df_ap.year == selected_date]
fig = px.treemap(filtered_df, path=[px.Constant("Coop"),"CCM_HC_TEXT" ,"CCM_CATEGORY_TEXT","CCM_SUBCATEGORY_TEXT",'MARKE_TEXT'], values='NU_AP',
color_continuous_scale=[(0, "red"), (0.5, "white"), (1, "green")],
color_continuous_midpoint=1, color=df_tree.INDEX_COLOR_NU, width=3840, height=1750)
fig.update_layout(margin = dict(t=100, l=50, r=25, b=25))
return fig
if __name__ == '__main__':
app.run_server(debug=True)
I want to be able to change the Date in the Dashboard so that the Treempa gets updatet.
But in the Dash Dashboard i get this error enter image description here
Traceback (most recent call last):
File "C:\Dev\py\Dashboard heatmap dev folder\from dash import dash, dcc, html.py", line 132, in update_figure
filtered_df = df_ap[df_ap.year == selected_date]
File "C:\Users\DANL2\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\generic.py", line 5907, in __getattr__
return object.__getattribute__(self, name)
AttributeError: 'DataFrame' object has no attribute 'year'
How do i need to edit the code so it Works ?
vp and ap are the two dates that i want to edit so that i can change the different Dates to compare.
I want to campare the two dates and display the difference in Sales. the Treemap plot works but the app callback or the def update_figure dont works i can't change the timeframe in the dashboard so that the codes get updated.
Related
I am rendering a scattermapbox using plotly in my Flask / Dash Application. I have set a default zoom level and lat,long coords. As the user pans the map via the plotly interface and changes the zoom level, I'd like to update the map with points and data layer.
Here's some code for reference:
import pandas as pd
import geopandas as gpd
# import mapbox
import requests
import plotly.graph_objects as go
# Update with host url
df_geo = gpd.GeoDataFrame.from_features(
requests.get(
"https://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_050_00_20m.json"
).json()
)
import plotly.graph_objects as go
fig = go.Figure(
go.Choroplethmapbox(
geojson=df_geo.set_index("GEO_ID")["geometry"].__geo_interface__,
locations=df_geo["GEO_ID"],
z=df_geo["CENSUSAREA"],
autocolorscale=False,
colorscale="Viridis",
zmin=df_geo["CENSUSAREA"].min(),
zmax=df_geo["CENSUSAREA"].quantile(0.95),
marker_line_width=0,
colorbar={"orientation": "h", "x": 0.5, "yanchor": "middle", "y": 0.1},
)
)
fig.update_layout(
mapbox_style="carto-positron",
# mapbox_accesstoken=token,
mapbox_zoom=3,
mapbox_center={"lat": 37.0902, "lon": -95.7129},
margin={"r": 0, "t": 0, "l": 0, "b": 0},
)
fig.show()
My question is, how do I obtain the geometries / bbox or lat,longs coords of the current map view?
Links to docs for reference:
https://plotly.com/python/reference/#scattermapbox
https://dash.plotly.com/dash-core-components/graph
relayoutData on a mapbox does return center and coordinates
have demonstrated by inserting this into trace using client side callback. This is working, however to improve efficiency I really wants to just update the figure rather than re-render it.
import pandas as pd
import geopandas as gpd
import requests
import plotly.graph_objects as go
from jupyter_dash import JupyterDash
import dash
from dash.dependencies import Input, Output, State
import json
# Update with host url
df_geo = gpd.GeoDataFrame.from_features(
requests.get(
"https://eric.clst.org/assets/wiki/uploads/Stuff/gz_2010_us_050_00_20m.json"
).json()
)
fig = go.Figure(
[
go.Choroplethmapbox(
geojson=df_geo.set_index("GEO_ID")["geometry"].__geo_interface__,
locations=df_geo["GEO_ID"],
z=df_geo["CENSUSAREA"],
autocolorscale=False,
colorscale="Viridis",
zmin=df_geo["CENSUSAREA"].min(),
zmax=df_geo["CENSUSAREA"].quantile(0.95),
marker_line_width=0,
name="choropleth"
# colorbar={"orientation": "h", "x": 0.5, "yanchor": "middle", "y": 0.1},
),
go.Scattermapbox(
name="scatter", marker={"size": 30, "color": "red", "opacity": 1}
),
]
)
fig.update_layout(
mapbox_style="carto-positron",
# mapbox_accesstoken=token,
mapbox_zoom=3,
mapbox_center={"lat": 37.0902, "lon": -95.7129},
margin={"r": 0, "t": 0, "l": 0, "b": 0},
datarevision=0,
height=300,
width=600,
autosize=False,
)
# Build App
app = JupyterDash(__name__)
app.layout = dash.html.Div(
[
dash.dcc.Checklist(
options=[{"label":"refesh", "value":"yes"}],
id="refresh",
),
dash.dcc.Graph(id="mapbox_fig", figure=fig),
dash.html.Div(
id="debug_container",
),
dash.dcc.Store(
id="points-store",
data={
"lat": [],
"lon": [],
},
),
]
)
#app.callback(
Output("points-store", "data"),
Output("debug_container", "children"),
Input("mapbox_fig", "relayoutData"),
Input("refresh","value")
)
def mapbox_cb(mapbox_cfg, refresh):
try:
refresh = refresh[0]=="yes"
except Exception:
refresh = False
if mapbox_cfg and "mapbox.zoom" in mapbox_cfg.keys() and refresh:
bbox = np.array(mapbox_cfg["mapbox._derived"]["coordinates"])
# bbox = bbox * .8
data = {
"lon": bbox[:, 0].tolist() + [mapbox_cfg["mapbox.center"]["lon"]],
"lat": bbox[:, 1].tolist() + [mapbox_cfg["mapbox.center"]["lat"]],
}
return data, [
dash.html.Pre(json.dumps(mapbox_cfg, indent=2)),
dash.html.Pre(json.dumps(data, indent=2)),
]
else:
raise dash.exceptions.PreventUpdate
app.clientside_callback(
"""
function(data, fig) {
fig.data[1]['lat'] = data['lat'];
fig.data[1]['lon'] = data['lon'];
fig.layout.datarevision = fig.layout.datarevision + 1;
/* return fig; */
return JSON.parse(JSON.stringify(fig));
}
""",
Output("mapbox_fig", "figure"),
Input("points-store", "data"),
State("mapbox_fig", "figure"),
)
app.run_server(mode="inline")
Can somebody give me a hint of why this part of my go.Choropleth code is not working?
I'm trying to make my country's borders a little more thicker and black, but it's not working and I don't know what else I could be missing on this layout specs... Here is my map code section and below it you can check a zoomed part of the map generated. Notice the country's borders are still thin and grey, why it does not change?
map_fig_layout = {'coloraxis_colorbar': {'title': 'População (%)',
'thickness': 20,
'ticklabelposition':'outside bottom'},
'margin': {'r':0, 'l':0, 't':0, 'b':0},
'template': 'plotly_dark',
'geo':{'projection': go.layout.geo.Projection(type ='natural earth'),
'landcolor': '#262626',
'showcountries':True,
'showsubunits':True,
'subunitcolor': 'black',
'subunitwidth': 4,
'resolution':110,
'visible':True,
'countrywidth': 4,
'countrycolor' : 'black'},
'uirevision':'not_tracked_key'}
map_graph = go.Figure({'data':[ go.Choropleth(locations = dff['Code'],
z = dff['população_%'], # a column of dff
hovertext = dff['Entity'],
zmin = 0,
zmax = 100,
colorscale = make_colorscale( ['#F53347','#E6C730','#2FF5A8'] ),
geo = 'geo') ],
'layout': map_fig_layout})
Try adding this line to your code:
fig.update_traces(marker_line_width=2.0, selector=dict(type='choropleth'))
or in your case:
map_graph.update_traces(marker_line_width=2.0, selector=dict(type='choropleth'))
You can additionally control the opacity, if so desired:
E.g.,
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
dtype={"fips": str})
import plotly.express as px
fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',
color_continuous_scale="Viridis",
range_color=(0, 12),
scope="usa",
labels={'unemp':'unemployment rate'}
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.update_traces(marker_line_width=3.0, marker_opacity=0.6, selector=dict(type='choropleth'))
fig.show()
Docs References
https://plotly.com/python/reference/choropleth/#choropleth-marker
using your code (make sure you format it to be PEP8 compliant for future questions)
sourced some data from kaggle to make this a re-producible example
examples of subunits are counties / regions in a country
import kaggle.cli
import sys, requests
import pandas as pd
from pathlib import Path
from zipfile import ZipFile
import urllib
import plotly.graph_objects as go
from plotly.colors import make_colorscale
# fmt: off
# download data set
url = "https://www.kaggle.com/mohaiminul101/population-growth-annual"
sys.argv = [sys.argv[0]] + f"datasets download {urllib.parse.urlparse(url).path[1:]}".split(" ")
kaggle.cli.main()
zfile = ZipFile(f'{urllib.parse.urlparse(url).path.split("/")[-1]}.zip')
dfs = {f.filename: pd.read_csv(zfile.open(f)) for f in zfile.infolist()}
# fmt: on
dff = dfs["world_population_growth.csv"].rename(
columns={"Country Code": "Code", "2019": "população_%", "Country Name": "Entity"}
)
dff["população_%"] = dff["população_%"] * 100
map_fig_layout = {
"coloraxis_colorbar": {
"title": "População (%)",
"thickness": 20,
"ticklabelposition": "outside bottom",
},
"margin": {"r": 0, "l": 0, "t": 0, "b": 0},
"template": "plotly_dark",
"geo": {
"projection": go.layout.geo.Projection(type="natural earth"),
"resolution": 110,
"visible": True,
},
"uirevision": "not_tracked_key",
}
map_graph = go.Figure(
{
"data": [
go.Choropleth(
locations=dff["Code"],
z=dff["população_%"], # a column of dff
hovertext=dff["Entity"],
zmin=0,
zmax=100,
marker={"line":{"width":4, "color":"black"}},
colorscale=make_colorscale(["#F53347", "#E6C730", "#2FF5A8"]),
)
],
"layout": map_fig_layout,
}
)
map_graph
I have the below dataframe:
When I convert this to a dict and then use it to populate a dash datatable, the field driver becomes joined as below
I want the elements in the driver field to be comma-separated. How can I do this? My current code is below:
import dash
import dash_table
import pandas as pd
import dash_bootstrap_components as dbc
import dash_html_components as html
## Display Settings
pd.set_option("max_columns",20)
pd.set_option("max_colwidth", 50)
pd.set_option("display.width", 2000)
pd.set_option("max_rows", 100)
import dash
import dash_html_components as html
import pandas as pd
brand_name = ['merc', 'bmw']
driver = [['driver1', 'driver2'], ['driver3', 'driver14']]
df = pd.DataFrame({'brand_name':brand_name, 'driver': driver})
print(df)
df_dict = df.to_dict('records')
app = dash.Dash(__name__)
app.layout = dbc.Card(
dbc.CardBody(
[
dash_table.DataTable(
id='homepage-table',
data=df_dict,
columns=[
{'name': 'brand_name', 'id':'brand_name'},
{'name': 'driver', 'id':'driver', },
],
style_cell={'textAlign': 'left', 'padding': '5px'},
style_data={
'whiteSpace': 'normal',
'height': 'auto',
'lineHeight': '18px',
'width': '22px',
'fontSize': '14px'
},
style_header={
'backgroundColor': 'rgb(230, 230, 230)',
'fontWeight': 'bold',
'lineHeight': '40px',
'fontSize' : '18px',
'padding-left': '5px'
},
style_data_conditional=[
{'if':
{
'row_index': 'odd'
},
'backgroundColor': 'rgb(248, 248, 248)'
},
],
)]))
if __name__ == '__main__':
app.run_server(debug=True)
Instead of this:
driver = [['driver1', 'driver2'], ['driver3', 'driver14']]
df = pd.DataFrame({'brand_name':brand_name, 'driver': driver})
do something like this:
drivers = [["driver1", "driver2"], ["driver3", "driver14"]]
drivers_comma_separated = [x[0] + ", " + x[1] for x in drivers]
df = pd.DataFrame({"brand_name": brand_name, "driver": drivers_comma_separated})
So the idea is if you loop through all elements in the drivers array, each element will be an array of two elements. Since each element in the outer array looks something like this ["driver1", "driver2"] we can simply concatenate the first and second element in the subarray with eachother with a comma in between.
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
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.