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.
Related
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.
I am implementing a flask application on which I want cytoscape graphs on it. I also want to dynamically update the data by sending a rest API call on the flask application and based on the data the cytoscape graph updates the graphs.
This is the code I have written to do so, but the update process is slow i.e. it receives the data but that data isn't updated on the dash code.
import dash # pip install dash
import dash_cytoscape as cyto # pip install dash-cytoscape==0.2.0 or higher
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Output, Input
import pandas as pd # pip install pandas
import plotly.express as px
import requests
from flask import Flask, request
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
server = Flask(__name__)
app1 = dash.Dash(__name__, server=server, external_stylesheets=external_stylesheets)
#server.route('/data', methods=['POST'])
def query_example():
global data_out
data = request.get_data()
data = (literal_eval(data.decode('utf8')))["data"]
print("Data Received")
with open('topology_data.pkl', 'wb') as f:
pickle.dump(data, f)
return {"Data":True}
with open('topology_data.pkl', 'rb') as f:
data_out = pickle.load(f)
app1.layout = html.Div([
html.Div([
cyto.Cytoscape(
id='org-chart',
layout={'name': 'breadthfirst'},
style={'width': '100%', 'height': '500px'},
elements=data_out,
stylesheet=[
# Group selectors
{
'selector': 'node',
'style': {
'content': 'data(label)',
'background-color': 'green',
'line-color': 'green'
}
},
{
'selector': 'edge',
'style': {
'background-color': 'green',
'line-color': 'green',
'label': 'data(label)'
}
},
{
'selector': '[weight = 1]',
'style': {
'line-color': 'red'
}
}
]
)
], className='six columns'),
], className='row')
if __name__ == '__main__':
app1.run_server(debug=True)
Please tell me a solution to integrate the data receiving process using the REST API and updating the data on the graphs.
You need to use callbacks to update the data.
#app.callback(Output('org-chart', 'elements'),
[Input("button", "n_clicks")],
def update_data(nclicks):
"""Retrieves data from api call
Parameters
----------
nclicks : int | None
The number of times the button was pressed.
Used to prevent initial update with empty state.
"""
if nclicks in [0, None]:
raise PreventUpdate
else:
data = api_call()
return data
You can find a lot more details and an example on https://dash.plotly.com/cytoscape/callbacks under "Adding and removing elements"
You need to add a button in your app layout of course
html.Button('Make api call', id='button', n_clicks=0)
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.
I'm trying to build a multi page Dash App. When I run the following code, everything works except it won't route to my /dash_1 or /dash_2 urls. Was wondering if someone could help me out.
My structure looks like this:
dash-project/
app1/
app.py
app2/
app.py
server.py
run.py
My run.py code is
from app import server as application
from app import app
import app_1.dash_1
import app_2.dash_2
My app.py code is:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from werkzeug.wsgi import DispatcherMiddleware
import os
import pandas as pd
import dash
import flask
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objs as go
from analysis import *
server=flask.Flask(name)
app = dash.Dash(name)
app.config.suppress_callback_exceptions = True
app.css.append_css({
‘external_url’: ‘https://codepen.io/chriddyp/pen/bWLwgP.css’
})
My dash_1.py code is:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.graph_objs as go
from analysis import *
from app import app, server
app = dash.Dash(name='dash_1', sharing=True,
url_base_pathname='/dash_1', csrf_protect=False)
app.config['suppress_callback_exceptions']=True
df = pd.read_csv('/Users/ds/app_1/main.csv')
layout = html.Div([
dcc.Graph(
id='Senators ',
figure={
'data': [
go.Scatter(
x=df[df['candidate'] == i]
['contributor_individual'],
y=df[df['candidate_name'] == i]['contributor'],
#z=df[df['candidate_name'] == i]['contributor'],
text=df[df['candidate_name'] == i]['contributorl'],
mode='markers',
opacity=0.7,
marker={
'size': 15,
'line': {'width': 0.5, 'color': 'white'}
},
name=i
) for i in df.candidate_name.unique()
],
'layout': go.Layout(
xaxis={'title': 'Contributor '},
yaxis={'title': 'Contributor '},
#margin={'l': 40, 'b': 40, 't': 10, 'r': 10},
#legend={'x': 0, 'y': 1},
hovermode='closest'
)
}
)
])
layout = html.Div(children=[
html.H1(children='Senators '),
html.Div(children='''
God Bless.
'''),
dcc.Graph(
id='main.csv',
figure={
'data': [
{'x':df['candidate'], 'y': df['sectorl'], 'type': 'bar'},
{'x':df['candidate'], 'y': df['industry'], 'type': 'bar'},
{'x':df['candidate'], 'y': df['contributor'], 'type': 'bar'},
],
'layout': {
'title': 'Let Them Eat...'
}
}
)
])
My dash_2.py code is
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
from app import app, server
app = dash.Dash(name='dash_2', sharing=True,
url_base_pathname='/dash_2', csrf_protect=False)
app.config['suppress_callback_exceptions']=True
df = pd.read_csv('/Users/ds/app_2/slice.csv')
layout = html.Div(children=[
html.H1(children='Bars'),
html.Div(children='''
One Bite....
'''),
dcc.Graph(
id='slice.csv',
figure={
'data': [
{'x':df['Slice'], 'y': df['Score'], 'type': 'bar'},
],
'layout': {
'title': 'Bars'
}
}
)
])
Any help would be greatly appreciated - I can't seem to wrap my head around this - Thanks!
You need to pass your flask app to your Dash instance.
Like this.
app = dash.Dash(__name__, server=server)
So try importing server and include it as a parameter in your Dash instances in app1 and app2.
Like so:
from app import server
app = dash.Dash(name='dash_1', sharing=True,
url_base_pathname='/dash_1', csrf_protect=False, server=server)
app = dash.Dash(name='dash_2', sharing=True,
url_base_pathname='/dash_2', csrf_protect=False, server=server)
Hope it helps.
#Franrey Saycon is completely right. You were importing too many things. In case this is helpful to anyone, I created a tutorial that shows how to build a multipage Dash application, with explanations on folder/file structure and library imports.
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)