Adding drag and drop effects to a plotly map

@Bahageel88: So based on your old code, I made something as below:

import pandas as pd
import numpy as np
import dash
from dash import html 
from dash import dcc
import plotly.graph_objects as go
from dash.dependencies import Input ,Output
import dash_bootstrap_components as dbc
import plotly.express as px
import requests

# read in the data -------------I used URL to get automically updated data from the data source ---------------------
url="https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv"
df=pd.read_csv(url,error_bad_lines = False)
df=df.rename(columns={'iso_code':'Countrycode','location':'Country'})
df.dropna(subset=['Country','total_cases', 'new_cases','total_deaths','new_deaths','new_deaths_smoothed'],inplace=True)
df['date']=pd.to_datetime(df['date'])
df['Mortality Rate']=df['total_deaths']/df['total_cases']*100
df['Death Rate']=df['total_deaths']/df['population']*100
df_country2=df.groupby(['Countrycode','Country']).sum().reset_index()
yesterdays_date=df['date'].max()
df['date']=pd.to_datetime(df['date'], format='%Y-%m-%d')
date=df['date'].dt.strftime('%Y-%m-%d')
# plot the Maps :--------- this part of the code transfered here to reduce the load on the call back function ------------------
df['date']=pd.to_datetime(df['date'], format='%Y-%m-%d')
df_country=pd.pivot_table(df,('total_cases','new_cases','total_deaths'),index=['date','Countrycode','Country'],aggfunc=np.sum).reset_index()
df_country.sort_values(['date'],ascending=[True])
df_country=df_country[df_country['date']>'2020-01-04']
date=df_country['date'].dt.strftime('%Y-%m-%d')
df_country2=df.groupby(['Countrycode','Country']).sum().reset_index()
yesterdays_date=df['date'].max()

fig7 = px.choropleth(df_country2, locations="Countrycode", color = "total_cases",
                                        hover_name= "Country",
                                        hover_data = df_country2[['total_cases','new_cases','total_deaths']],
                                        projection="orthographic",
                                        color_continuous_scale=px.colors.sequential.OrRd_r)
fig7.update_layout(paper_bgcolor='#000000',geo=dict(bgcolor= '#000000'),
                                                title=f"Cumulative Cases since the start of pandemic untill {yesterdays_date}")
fig7.layout.template='plotly_dark'



app=dash.Dash(external_stylesheets=[dbc.themes.CYBORG],
              meta_tags=[{'name': 'viewport',
                            'content': 'width=device-width, initial-scale=1.0'}])
server=app.server
app.layout=dbc.Container([
    dbc.Row(
        dbc.Col(
        html.H2("COVID 19 DASHBOARD WITH REAL-TIME DATA ",className='text-center mb-4'),width=12)),
                          dcc.Graph(figure=fig7,id='map_1'),
    dbc.Row(
        html.Marquee("Get Daily Updated News About Covid 19 From Bahgeel Dashboard"), 
                              style = {'color':'red'}),
    dbc.Row([
        dbc.Col([html.Div(id='show_data')])
    ])
])

@app.callback(Output('show_data', 'children'),
          [Input('map_1', 'clickData')])

def update_line_chart(clickdata):
    if clickdata:
        points = clickdata['points'][0]['location']
        dff_z = df_country[df_country['Countrycode'] == points]
        fig = px.line(dff_z, x="date", y="total_deaths")
        return dcc.Graph(figure=fig)
if __name__=='__main__':
    app.run_server(debug=False, port=8000)

This one is the first load:

This one is after clicking on map:

Hope this help.

1 Like