✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚡️ Concerned about the grid? Kyle Baranko teaches how to predicting peak loads using XGBoost. Register for the August webinar!

Want to update table based on clickdata in map

My problem is that I want to update table based on the district I click on map but I am unable to do so.
If you can solve my problem that would be very useful for me.
Thanks in advance.

I am attaching the code as below:

“”"
Created on Fri May 1 15:03:23 2020

@author: Arnab
“”"

import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_table
from dash_table import DataTable

from dash.exceptions import PreventUpdate
from dash.dependencies import Output, Input, State
import pandas as pd
import plotly.express as px
import mapboxgl
import plotly.offline as pyo
import plotly.graph_objs as go
import json
from urllib.request import urlopen

with urlopen(“https://raw.githubusercontent.com/HindustanTimesLabs/shapefiles/master/state_ut/westbengal/district/westbengal_district.json”) as ra:
counties = json.load(ra)
counties[“features”][0]

counties[‘features’][0][“properties”][‘district’]

df = pd.read_csv(“https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv”)
#dtype={“fips”: str})
df=pd.read_csv(“DWP.csv”)
df1=df.filter([‘District’, ‘Population’])
df2=df.filter([‘Population’, ‘Sex Ratio’,‘Density’]).mean().reset_index()
df2.columns.values[0:2]=[‘Metrices’,‘values’]

access_token=“pk.eyJ1IjoiYXJuYWI5MyIsImEiOiJjazlueHAxdW8wNG54M2ZwbXgzOGFlZGtqIn0.YE9jS52NmDrNsdpMeO9X_w”
mapboxgl.accessToken = access_token
#px.set_mapbox_access_token(open(".mapbox_token").read())

fig = px.choropleth(df1, geojson=counties, color=‘Population’,
locations=‘District’,
projection=“mercator”,
featureidkey=“properties.district”,
labels={‘Population’:‘population in million’},
height=600,
width=800
)
fig.update_geos(fitbounds=“locations”, visible=False)
fig.show()
fig.update_layout(mapbox_accesstoken=access_token,margin={“r”:0,“t”:0,“l”:0,“b”:0})
fig.show()

app = dash.Dash(external_stylesheets=[‘https://codepen.io/chriddyp/pen/bWLwgP.css’])
app.config[‘suppress_callback_exceptions’] = True
app.layout = html.Div([

    html.Div([
     html.Div([
    dcc.Graph(id="map",
              figure=fig),
                ],className="six columns"),
                    
               html.Div([
               html.H3("Average Value for All Districts"),
    dash_table.DataTable(
            id='table',
            style_cell={'whiteSpace': 'normal','height': 'auto'},
    data=df2.to_dict('records'),
    columns=[{"name": i, "id": i} for i in df2.columns],
    style_cell_conditional=[
                    {
        'if': {'column_id': i},
        'textAlign': 'left'
        } for i in ['Metrices','values']
        ],
            style_data_conditional=[
                    {
                            'if': {'row_index': 'odd'},
                            'backgroundColor': 'rgb(248, 248, 248)'
                            }
                    ],
            style_header={
                    'backgroundColor': 'rgb(230, 230, 230)',
                    'fontWeight': 'bold'
                    },
            style_as_list_view=True,
            
                ),
             ], className="six columns"),
          ],className="row"),

])
#@app.callback(Output(‘map’, ‘figure’))
# [Input(‘map’, ‘figure’)])
@app.callback(
Output(‘table’,‘data’),
[Input(‘map’, ‘figure’)],
[State(“map”, “clickData”)]
)
def display_click_data(choro_fig,choro_click):

if choro_click is not None:
    dis=choro_click['features'][0]["properties"]['district']
    df3=df[df.District==dis]
    df3=df3.filter(['Population', 'Sex Ratio','Density']).mean().reset_index()
    df3.columns.values[0:3]=['Metrices','values for dis']
            
        
    data=df2.merge(df3)
    
    return data
else:
   raise PreventUpdate

=============================================================================

def update_graph(data):

# Do some updates

if data is None:

return

else:

return

=============================================================================

# Expected result: mapbox click event data geojson properties

if name == ‘main’:
app.run_server(debug=False)

Note:After clicking on district on map the table should look like this…I am attaching the screenshot in below

i come up with the same problem…dude…did you overcome that problem now?

Yes I have come up with solution,hope it will help you.

For (DWP.CSV)

-- coding: utf-8 --

“”"
Created on Fri May 1 15:03:23 2020

@author: Arnab
“”"

import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_table
from dash_table import DataTable

from dash.exceptions import PreventUpdate
from dash.dependencies import Output, Input, State
import pandas as pd
import plotly.express as px
import mapboxgl
import plotly.offline as pyo
import plotly.graph_objs as go
import json
from urllib.request import urlopen

with urlopen(“https://raw.githubusercontent.com/HindustanTimesLabs/shapefiles/master/state_ut/westbengal/district/westbengal_district.json”) as ra:
counties = json.load(ra)
counties[“features”][0]

counties[‘features’][0][“properties”][‘district’]

#df = pd.read_csv(“https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv”)
#dtype={“fips”: str})
df=pd.read_csv(“DWP.csv”)
df1=df.filter([‘District’, ‘Population’])
df2=df.filter([‘Population’, ‘Sex Ratio’,‘Density’]).mean().reset_index()

access_token=“Your API Token”
mapboxgl.accessToken = access_token
#px.set_mapbox_access_token(open(".mapbox_token").read())

fig = px.choropleth(df1, geojson=counties, color=‘Population’,
locations=‘District’,
projection=“mercator”,
featureidkey=“properties.district”,
labels={‘Population’:‘population in million’},
height=600,
width=800
)
fig.update_geos(fitbounds=“locations”, visible=False)
fig.show()
fig.update_layout(mapbox_accesstoken=access_token,margin={“r”:0,“t”:0,“l”:0,“b”:0},clickmode=“event+select”)
fig.show()

columns = [
{“id”: 0, “name”: “Metrices”},
{“id”: 1, “name”: “All District Average”},
{“id”: 2, “name”: “Selected District Average”}]

app1 = dash.Dash(external_stylesheets=[‘https://codepen.io/chriddyp/pen/bWLwgP.css’])
app1.config[‘suppress_callback_exceptions’] = True
app1.layout = html.Div([

    html.Div([
     html.Div([
    dcc.Graph(id="map",
              figure=fig),
                ],className="six columns"),
                    
               html.Div([
               html.P("Select one district from map and compare between the average of all districts and selected district Average"),
    dash_table.DataTable(
            id='table',
            #style_cell={'whiteSpace': 'normal','height': 'auto'},
            data=[],

=============================================================================

style_cell_conditional=[

{

‘if’: {‘column_id’: i},

‘textAlign’: ‘left’

} for i in [‘Metrices’,‘values’]

],

             style_data_conditional=[
                    {
                            'if': {'row_index': 'odd'},
                            'backgroundColor': 'rgb(248, 248, 248)'
                            }
                    ],
             style_header={
                     'backgroundColor': 'rgb(230, 230, 230)',
                     'fontWeight': 'bold'
                     },

=============================================================================

            #style_as_list_view=True,
            
                ),
             ], className="six columns"),
          ],className="row"),

])
#@app.callback(Output(‘map’, ‘figure’))
# [Input(‘map’, ‘figure’)])
@app1.callback(
[Output(‘table’,‘data’),Output(‘table’, ‘columns’)],
[Input(‘map’, ‘clickData’)]

)
def display_click_data(choro_click):

if choro_click is None:
    
    return df2.values, columns[0:2]
else:
    dis=choro_click['points'][0]['location']
    df3=df[df.District==dis]
    df3=df3.filter(['Population', 'Sex Ratio','Density']).mean().reset_index()
    data=df2.merge(df3,on='index')
    
    

    return data.values, columns[0:3]

if name == ‘main’:
app1.run_server(debug=False)