Quantcast
Channel: 🎛️ Dash - Plotly Community Forum
Viewing all articles
Browse latest Browse all 6271

Want to update table based on clickdata in map

$
0
0

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

1 post - 1 participant

Read full topic


Viewing all articles
Browse latest Browse all 6271

Trending Articles