Adding drag and drop effects to a plotly map

Could you post what did you try. I think with code, I can help you faster.

1 Like

Ok I will send you my code for the map and for the line chart
Thank you very much indeed @hoatran @jinnyzor

1 Like

@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

I am really wordless really delighted to have you as a teacher thank you very much indeed for your extraordinary contribution and spirit for assistance
Thanks this is
Exactly What I want
Thank my dear @hoatran
and for all of you guys

1 Like

Good evening Dear @hoatran
thank you for your answer I implemented your answer but it threw an exception which simply states;
Traceback (most recent call last):
File “C:\Users\ic04\Desktop\unemployment dashboard\app.py”, line 22, in
app.layout=dbc.Container([
File “C:\Users\ic04\Anaconda3\lib\site-packages\dash\dash.py”, line 606, in layout
_validate.validate_layout_type(value)
File “C:\Users\ic04\Anaconda3\lib\site-packages\dash_validate.py”, line 386, in validate_layout_type
raise exceptions.NoLayoutException(
dash.exceptions.NoLayoutException: Layout must be a dash component or a function that returns a dash component.
PS C:\Users\ic04\Desktop\unemployment dashboard>
how to resolve this problem ?
with best regards

Can you attach your code?

Hm sorry but can you format your code or upload it to somewhere to read (include dataframe)

1 Like

Ok its available on my git hub repo

@Bahageel88: just remove the trailing comma of dbc.Container

From:

app.layout=dbc.Container([
                dbc.Row(dbc.Col(html.H3("Unemployement Rate Worldwide Since 1991",className='text-center mb-4'),width=12)),
                dbc.Row( html.Marquee("Unemployment Rates Worldwide Since 1991 -Bahageel Dashboard-Data Compiled from World Bank "), style = {'color':'cyan'}), 
                dbc.Row([dbc.Col([html.H6(['Choose Years to view Unemployment Rate :']),]),
                                      html.Div(dcc.RangeSlider(id='yearslider',
                                                 marks={str(year):{'label':str(year),'style':{"color": "#7fafdf"},} for year in YEARS},
                                                        step=1
                                                        ,
                                                 min=min(YEARS),
                                                 max=max(YEARS),
                                                 value=[2010,2020],
                                                 dots=True, 
                                                 allowCross=False, 
                                                 disabled=False, 
                                                 pushable=2, updatemode='drag', 
                                                 included=True,vertical=False,
                                                 verticalHeight=900, className='None', 
                                                 tooltip={'always_visible':False, 'placement':'bottom'}),

                                                 style={'width':'95%'})]),
              dbc.Row([dbc.Col([dcc.Graph(id="map",figure={})]),dbc.Col(html.Div(id='show_data'))]),
              ]),

to

app.layout=dbc.Container([
                dbc.Row(dbc.Col(html.H3("Unemployement Rate Worldwide Since 1991",className='text-center mb-4'),width=12)),
                dbc.Row( html.Marquee("Unemployment Rates Worldwide Since 1991 -Bahageel Dashboard-Data Compiled from World Bank "), style = {'color':'cyan'}), 
                dbc.Row([dbc.Col([html.H6(['Choose Years to view Unemployment Rate :']),]),
                                      html.Div(dcc.RangeSlider(id='yearslider',
                                                 marks={str(year):{'label':str(year),'style':{"color": "#7fafdf"},} for year in YEARS},
                                                        step=1
                                                        ,
                                                 min=min(YEARS),
                                                 max=max(YEARS),
                                                 value=[2010,2020],
                                                 dots=True, 
                                                 allowCross=False, 
                                                 disabled=False, 
                                                 pushable=2, updatemode='drag', 
                                                 included=True,vertical=False,
                                                 verticalHeight=900, className='None', 
                                                 tooltip={'always_visible':False, 'placement':'bottom'}),

                                                 style={'width':'95%'})]),
              dbc.Row([dbc.Col([dcc.Graph(id="map",figure={})]),dbc.Col(html.Div(id='show_data'))]),
              ])

Thank you very much indeed I am really embarrassed with these persistent questions I tormented you brother
thank very much indeed

1 Like

@Bahageel88 : You’re welcome :smiley:, if it solved your problem then mark my answer as solution. Thank you

2 Likes

Thank you very much indeed for your kind assistance
With best regards