Related
I would like to display/use/put my LDA model in my dash app. Here's the code for the LDA model which works and that I've saved in html on my computer :
# Libraries
import spacy
from gensim.corpora import Dictionary
from gensim.models import LdaModel
import pyLDAvis.gensim_models
import pandas as pd
nlp_teletravail = spacy.load("fr_core_news_sm")
# Create df for the example
data = [['tweet content in french'], ['tweet 2 content in french'], ['tweet 3 content in french']] # lots of tweets and other columns but not useful for the example
# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Preprocessed_tweets'])
spacy_docs_teletravail = list(nlp_teletravail.pipe(df["Preprocessed_tweets"]))
# Create empty list called docs_teletravail
docs_teletravail = []
# Pre processing
# For each document in spacy_docs_teletravail
for doc in spacy_docs_teletravail:
# We create empty list called tokens_teletravail
tokens_teletravail = []
# for each token in each document of spacy_docs_teletravail
for token in doc:
# pre processing 1 and 2
if len(token.orth_) > 2 and not token.is_stop:
# pre processing 3 and 4
tokens_teletravail.append( token.lemma_.lower() )
# append results of tokens_teletravail in docs_teletravail
docs_teletravail.append( tokens_teletravail )
dictionary_teletravail = Dictionary(docs_teletravail)
corpus_teletravail = [ dictionary_teletravail.doc2bow(doc) for doc in docs_teletravail]
model_teletravail_passes_5 = LdaModel(corpus=corpus_teletravail,
id2word=dictionary_teletravail,
num_topics=10,
chunksize=1000,
passes=5,
random_state=1)
vis_data_teletravail = pyLDAvis.gensim_models.prepare(model_teletravail_passes_5, corpus_teletravail, dictionary_teletravail, sort_topics=False)
# Export the graph and store it where we want in our computer
pyLDAvis.save_html(vis_data_teletravail, 'C:/Users/mario/Downloads/lda_model_passes_5.html')
Maybe you can add content for the tweets (random sentences that you can find on the internet). I think I can't load my html file on the post but don't hesitate to tell me if it's possible and I'll do it so that you don't have to run the first part. And here's the code of my dash app where I have multiple tabs and subtabs but I don't put their content here because it's useless, you just have the code with the tabs (empty). I would like to put the LDA model in tab 3 (Latent Dirichlet Allocation Model) subtab 10 (LDA Model 10 topics). I left most of my attempts in comments to return the LDA model in subtab10 but nothing is happening (no errors, nothing appearing on the dash app). Thank you for your help !
# Needed libraries
#import pandas as pd
import dash
import dash_bootstrap_components as dbc
#import plotly.express as px
#import numpy as np
from dash import dcc, html
from dash.dependencies import Input, Output
from dash_bootstrap_templates import ThemeSwitchAIO, template_from_url
# Two different templates stored in variables for the dash app
template_theme1 = "cyborg"
template_theme2 = "lumen"
url_theme1 = dbc.themes.CYBORG
url_theme2 = dbc.themes.LUMEN
# Link which gives access to the templates
dbc_css = (
"https://cdn.jsdelivr.net/gh/AnnMarieW/dash-bootstrap-templates#V1.0.1/dbc.min.css"
)
# Create the app and define the main theme in external_stylesheets
app = dash.Dash(__name__, external_stylesheets=[url_theme1, dbc_css])
# Define a sentence that appears on the top left of the app in order to choose between the two proposed themes
header = html.P("Click if you want to change theme of graphics",style={'textAlign': 'left','font-size':'300','font-family':'helvetica'})
# Create the layout of the app
app.layout = html.Div([ # html Div to use html components (style, text, tabs, subtabs etc)
html.H1('Health consequences during covid-19 pandemic dashboard', style={'textAlign': 'center','font-size':'300','font-family':'helvetica'}),
dbc.Container( # dbc container and row to use dbc Col to define the different themes to choose
dbc.Row(
[
dbc.Col( # Define the two possible themes to choose
[
header, # header is the sentence that we've dehttps://stackoverflow.com/questions/64736956/how-to-use-iframe-in-dash-plotly-python-htmlfined earlier in header variable
ThemeSwitchAIO( # switch with icons
aio_id="theme", # id of the switch
themes=[url_theme1,url_theme2], # proposed themes that we've defined earlier
),
])])),
dcc.Tabs(id='tabs', value='Tab1', style={'background-color': 'black'}, children=[
# Create tabs and their sub tabs
dcc.Tab(label='Data information', id='tab1', value='Tab1', style={'textAlign': 'center', 'font-size':'100','font-family':'helvetica', 'background-color': 'black'},children =[ # First tab
dcc.Tabs(id="subtabs1", value='Subtab1',children=[ # Create sub tabs in the first tab
dcc.Tab(label='Basic information about the dashboard', id='subtab1', value='Subtab1',style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # First sub tab of tab 1
dcc.Tab(label='Number of collected tweets', id='subtab2', value='Subtab2',style={'textAlign': 'center', 'font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Second sub tab of tab 1
dcc.Tab(label='Number of collected tweets per month each year', id='subtab3', value='Subtab3',style={'textAlign': 'center', 'font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Third sub tab of tab 1
dcc.Tab(label='Wordcloud', id='subtab4', value='Subtab4',style={'textAlign': 'center', 'font-size':'100','font-family':'helvetica', 'background-color': 'black'})]) # Fourth sub tab of tab 1
]),
dcc.Tab(label='Sentiment Analysis', id='tab2', value='Tab2',style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}, children=[ # Create the Second tab
dcc.Tabs(id="subtabs2", value='Subtab2', children=[ # Create sub tabs for the second tab
dcc.Tab(label='Number or percentage of tweets according to sentiments', id='subtab5', value='Subtab5', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # First sub tab of tab 2
dcc.Tab(label='Percentage of tweets according to sentiments and time slots', id='subtab6', value='Subtab6', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Second sub tab of tab 2
dcc.Tab(label='Number or percentage of tweets according to sentiments and time slots', id='subtab7', value='Subtab7', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Third sub tab of tab 2
dcc.Tab(label='Number or percentage of tweets according to sentiments each year', id='subtab8', value='Subtab8', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'})]) # Fourth sub tab of tab 2
]),
dcc.Tab(label='Latent Dirichlet Allocation Model', id='tab3', value='Tab3',style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}, children=[ # Create the Third tab
dcc.Tabs(id="subtabs3", value='Subtab3', children=[
dcc.Tab(label='LDA Model interpretation', id='subtab9', value='Subtab9', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # First sub tab of tab 3
dcc.Tab(label='LDA Model 10 topics', id='subtab10', value='Subtab10', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Second sub tab of tab 3
dcc.Tab(label='LDA Model 5 topics', id='subtab11', value='Subtab11', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'})]) # Third sub tab of tab 3
]),
dcc.Tab(label='Network Graph', id='tab4', value='Tab4',style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}, children=[ # Create the fourth tab
dcc.Tabs(id="subtabs4", value='Subtab4', children=[
dcc.Tab(label='To determine', id='subtab13', value='Subtab13', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # First sub tab of tab 4
dcc.Tab(label='To determine', id='subtab14', value='Subtab14', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'}), # Second sub tab of tab 4
dcc.Tab(label='To determine', id='subtab15', value='Subtab15', style={'textAlign': 'center','font-size':'100','font-family':'helvetica', 'background-color': 'black'})]) # Third sub tab of tab 4
])
])
])
############################################ Tab 3 LDA MODEL
############### Sub tab 10 LDA Model 10 topics
# Callback for Tab 3 and subtab 10 LDA Model 10 topics
#app.callback(Output('subtab10', 'children'), # Output
[Input('subtabs3', 'value'), # Input
Input(ThemeSwitchAIO.ids.switch("theme"),"value")]) # Another input is the selected theme/template
# Create function to display lda model
def display_lda_subtab10(value,toggle): # 2 parameters value for which subtab and toggle for theme/template
if value == 'Subtab10':# If we are in subtab2 in tab 1 we return a graph
template = template_theme1 if toggle else template_theme2 # We define the theme selected
#lda_10_topics = html.Iframe(src='C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')
#return html.Div([dcc.Graph(figure=lda_10_topics)])
# https://stackoverflow.com/questions/64736956/how-to-use-iframe-in-dash-plotly-python-html
#return html.Div([dcc.Graph(id='example'),
# html.Iframe(src='C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')
# ])
#return html.Div([dcc.Graph(id='example'),
# html.Iframe(src=r'C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')
# ])
#https://stackoverflow.com/questions/68269257/local-html-file-wont-load-properly-into-dash-application
#return html.Div([html.Iframe(src="assets/lda_model_topics_10.html")])
# https://stackoverflow.com/questions/74534261/dash-include-custom-html-object
#lda_10_topics = html.Iframe(src=r'C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')
#with open("C:/Users/mario/Downloads/lda_model_passes_5_json.json",'r') as f:
#with open(lda_passes_5_json,'r') as f:
# return html.Div([dcc.Graph(figure=json.load(f))])
#return json.load(f)
#html.Iframe(src=r'static/lda_model_topics_10.html')
#html.Div([html.Iframe(src=r'C:/Users/mario/Desktop/M2 Health Data Science 2022 2023/Mémoire/Projet Pro M2 2022 2023/Codes_tests_apres_rapport_detape/LDA/lda_model_topics_10.html')])
# Run the dash app
if __name__ =='__main__':
app.run_server(debug=False)
I found the solution by creating a folder called assets on my computer. Then we put the lda.html file inside. After that you can add the following code in the function and it works (your python path should be the one where the folder 'assets" is) !
return html.Div([html.Iframe(src="assets/lda_model_topics_10.html")])
You might have to adjust height and width after : src="...", height=..., width=...
I am plotting some data points on a graph.
Output:
Now, I plotted some ambulance locations (Dataset is in two excel files) Does not work
As we can see above, the new plotted data as ambulance location is hidden due to previous plotted data. How do we solve this?
Here is my code (Dataset is in two excel files):
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import geopandas as gpd
from openpyxl import load_workbook
import numpy as np
import pandas as pd
from mplcursors import cursor
import numpy as np;
np.random.seed(0)
import seaborn as sns;
from matplotlib.pyplot import figure
import pandas as pd
import numpy as np
import io
file_loc_1 = "AgeGroupData_time_to_treatment.xlsx"
df_centroid_Coord = pd.read_excel(file_loc_1, index_col=None, na_values=['NA'])
df_centroid_Coord
file_loc2Amb = "Ambulance IDs.xlsx"
df_station = pd.read_excel(file_loc2Amb, index_col=None, na_values=['NA'], usecols="A:D")
df_station.rename(columns={'Longtitude':'x', 'Latitude':'y'}, inplace=True)
df_centroid_Coord['Ambulance_Treatment_Time'] = df_centroid_Coord ['Base_TT']
fig = px.scatter(df_centroid_Coord, x="x", y="y",
title="Southern Region Centroids",
color='Ambulance_Treatment_Time',
log_x=True,
size_max=60,
color_continuous_scale='Reds',
range_color=(0.5,2),
)
fig.update_traces(marker={'size': 4, 'symbol': 1})
fig.add_trace(go.Scatter(x=df_station['x'],
y=df_station['y'],
mode='markers+text',
text=df_station['Ambulance station name'],
textposition='top center',
showlegend=True,
marker=dict(
size=12,
symbol=2,
color='black'
)
)
)
fig.update_layout(width=1000, height=800, paper_bgcolor="LightSteelBlue")
fig.show()
Working Code: (Dataset is inside code)
import plotly.express as px
import plotly.graph_objects as go
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import geopandas as gpd
from openpyxl import load_workbook
import numpy as np
import pandas as pd
from io import StringIO
import numpy as np;
np.random.seed(0)
import seaborn as sns;
data = '''
x y Base_TT
14.1315559 55.75811117 1.871884861
14.66228957 57.02751992 1.599971112
14.49407157 56.06563489 1.307165278
13.21996788 55.4786748 1.411554445
14.00501286 55.72120854 1.968138334
12.73736102 56.71097302 1.309849028
14.56668525 56.74872925 1.719116945
13.24138764 56.41359089 2.000620417
14.94308088 56.54283706 1.668724723
14.5744739 56.05695327 1.266861528
13.06800876 56.6356658 1.58923875
14.69964193 56.47959746 1.960050139
13.02976922 55.48474858 1.2549575
13.16901029 56.23281882 1.429789167
13.05906805 55.85369617 1.553721944
13.7382052 55.60193648 1.326429166
13.72987233 56.34767237 1.709020555
14.58803736 56.29060354 1.444833472
13.1687123 55.90031115 1.527546805
15.02422205 56.27331725 1.692005
12.91010076 56.24668905 1.090544167
13.2053785 55.45149986 1.438993611
13.37256031 55.61560233 1.632310694
13.26737288 56.19829081 1.869085
13.23818589 55.42501479 1.646565973
14.50187617 56.70356708 1.880334584
14.70189174 56.19209891 1.31886875
13.34482545 56.27124013 1.81529125
12.8785792 55.94059005 1.418415555
12.93136079 55.85161507 1.40189875
12.89164916 55.99473803 1.45182125
13.10496461 56.22286779 1.456101528
15.38666411 56.9824605 1.922860277
13.32430726 56.00137807 1.941762638
13.51541698 56.45311516 1.768057778
15.0413443 57.17170192 2.024309722
12.8606001 55.97622841 1.401550417
13.46749777 56.03019927 1.883145
14.72922746 56.88394501 1.273883612
14.55821135 56.07486606 1.331545972
12.93914018 56.60663923 1.351015694
13.9743559 55.67602686 1.874753334
14.64564524 57.04544092 1.668993889
12.66824186 56.24236656 1.333240139
14.0105656 56.75454085 1.378468056
13.60274138 55.39377504 1.582678472
15.75049672 56.25307533 1.564625833
13.60115485 55.43869065 1.577717361
15.7653804 56.19008971 1.372651944
13.1832264 56.95189695 1.748949583
15.60524952 56.25387079 1.3378925
14.23746798 56.04634612 1.200910417
14.35058672 56.00206764 1.385281667
13.60986899 56.97533616 2.631095833
13.45346163 56.38047383 1.811332917
15.3486521 56.43454959 2.049025556
12.83048942 56.22734439 1.118363333
13.84310479 56.34878109 1.626188472
13.03675856 55.97916057 1.681367638
14.42929903 56.1012924 1.947557639
13.2062902 56.12552876 1.535386944
13.34357303 57.04397378 1.86576
14.03682213 57.00630325 1.720512917
15.18750805 56.64153377 1.769290139
14.47260163 56.46087204 2.272563194
15.44375218 56.24557042 1.541445833
14.46883407 56.73038276 1.778631806
13.10870739 55.81852133 1.51138625
12.86285426 56.80305259 1.40997375
13.49439127 56.98298455 2.250301528
13.70360937 56.16769145 1.196677639
14.08919483 55.52417158 1.591170417
13.55740496 55.77068518 1.535861945
14.18123581 55.66859517 1.996627778
15.23403607 56.25512928 1.548016667
15.70489096 56.40608375 2.047458055
14.37376278 56.55025699 2.067875139
14.502587 56.64966538 2.082391666
13.02508849 56.832684 1.706181111
13.14274787 55.77410524 1.375705139
14.84565179 56.5068175 1.885311528
14.20034005 56.28870701 1.691717361
13.8812731 55.59433892 1.5328325
14.14035572 56.80042421 1.561514584
13.76343201 55.80887467 1.749841528
13.89449225 56.25041347 1.46041875
15.17289149 57.00988892 1.521688473
14.77824552 56.9199763 1.376412361
13.27891612 55.57837586 1.622874028
14.24058672 56.70224862 1.666531805
14.37017794 56.76585965 2.005441666
13.52451801 55.79725389 1.521532778
13.71088665 55.46685563 1.222417361
14.9588848 56.96508403 1.38658
14.82826594 56.75834768 1.485242778
13.1940657 56.38595264 1.792493889
14.84402516 56.90210837 1.235783333
14.46031787 56.18229581 1.681354444
14.63590428 56.35364532 1.650511111
13.34460314 55.52535888 1.473964166
14.62952158 57.00946017 1.6048425
13.71970327 55.68262124 1.564198333
13.13107617 56.34907413 1.663111806
13.48159711 56.89298141 2.3218075
13.81128734 55.80934654 1.869087639
14.15612237 56.82748426 1.526720834
13.25994595 57.06979504 1.953888333
13.36341923 55.45371566 1.683035417
13.53607897 55.91421314 1.662510139
14.84502823 56.65954652 1.808187361
13.5819665 56.40896643 1.723420972
14.10802101 56.09040464 1.322613333
12.59101931 56.18696069 1.285278334
15.22304196 57.13557739 1.861801667
13.93212119 56.63709467 1.879722361
14.04083953 56.20670871 1.426582917
13.20977325 55.70320438 1.036230556
14.50691645 56.31726101 1.512323056
14.04385954 55.43396451 1.518698611
14.62176554 56.14695594 1.436045973
12.94595993 56.48094227 1.284676667
13.43761668 56.76664816 2.052952223
13.4881 55.91363347 1.748883611
13.30499035 56.44143388 1.901664722
14.59756066 56.91952527 1.202981944
13.2574875 55.70389081 1.129174861
13.47396568 56.67724669 2.238806528
12.73718764 56.44136418 1.683367917
13.83580567 55.5220256 1.431533473
14.59492984 57.16207179 1.922699306
14.64495938 57.11730653 1.864279583
14.4312567 57.05363464 1.896975417
13.41144319 55.83179083 1.403585
14.22184539 56.81892717 1.746305417
13.50202498 56.38107009 1.659256389
12.68761018 56.18880561 1.355646945
14.94282338 56.71353347 1.63897125
15.02454518 56.77643118 1.68773
15.57297141 56.25402442 1.414539028
12.964589 56.43631667 1.382988472
13.45825395 55.45494721 1.820561111
14.63191383 56.76690666 1.694100278
13.14103724 55.81002734 1.48003625
15.21769188 56.21922061 1.580773194
14.10257692 55.63210186 1.773493889
13.17668301 56.07117614 1.724194167
15.84692703 56.23448315 1.807886528
13.44350876 55.42779971 1.808543611
15.1857457 56.28216487 1.575294861
13.31802754 56.51349734 1.770477639
12.8935671 56.83951966 1.609666389
15.86386582 56.27030588 2.006792778
13.34532169 55.88483834 1.414042917
14.02227635 55.66743196 1.754815834
15.54234554 56.37096273 1.768464167
14.17727266 55.85726695 1.794488889
13.02668442 55.86216815 1.630864584
14.02130349 56.97024678 1.49533125
14.70175234 56.21006795 1.380317916
13.4056505 56.3618967 1.847926389
14.52330627 56.29935591 1.458468611
15.45924302 56.19160552 1.353913194
13.64578835 55.52007228 1.636670139
15.54272866 56.39791466 1.825142222
13.77315439 57.01298115 2.218526667
15.81485761 56.2436834 1.651075833
13.50857285 55.7970615 1.55940875
13.2405817 55.37112529 1.525214028
13.77433597 56.9770554 1.827475
13.02797412 55.52067001 1.181577917
14.94264555 56.83032305 1.482392778
14.79657364 56.5696361 1.996696389
14.42283094 56.53252583 2.141961944
13.30174382 55.41692656 1.592043888
12.91793298 56.39959593 1.43073125
12.90894568 56.85775049 1.762173056
13.75637136 56.52764363 1.831847639
14.47776811 56.08353697 1.370715
13.22852136 55.64056743 1.272487639
13.58430026 56.34609492 1.82778375
13.49063969 56.66846469 2.12446875
13.10834154 56.8070164 1.948958889
14.04485542 56.0450056 1.215075973
14.13354678 55.66826782 1.915392223
15.50829522 56.24532218 1.578224028
15.13989252 56.99196316 1.574268333
14.38668231 56.75695784 1.967270138
14.37062878 56.73890974 2.157887638
14.17479551 55.97406075 1.204406945
12.94883204 55.51937 1.279889722
13.58529757 56.31914974 1.783001805
13.27981504 55.91988672 1.720325555
13.59881528 56.83145749 2.139697778
13.59915061 56.82247642 2.074659723
13.40296577 56.03836683 1.7947475
14.29429163 55.57045392 1.731105417
12.80578871 56.65827783 1.060809167
14.53129548 56.96421286 1.476721806
13.26306176 55.57815222 1.600958055
14.49804298 56.99103484 1.81823625
13.4719759 55.50904044 1.673925972
13.91167961 56.78067047 1.325035834
14.12918279 56.57573794 1.790625556
14.04255435 55.48787141 1.424878194
14.04189635 56.80869138 1.407714861
14.79691051 56.50674739 1.909035139
13.45649939 55.4998595 1.623631389
14.03861222 55.6495892 1.614189445
14.04342496 55.45193356 1.590481667
13.71133755 56.89556193 2.093918334
14.17229995 56.09085224 1.279623194
13.6748116 56.06854362 1.526770972
12.70417007 56.71935248 1.316963472
13.30434416 56.0909687 1.68737375
14.56792192 56.64092518 2.210113889
13.34417417 55.91178236 1.465459028
14.08469442 56.39572484 1.527290833
13.5484731 55.58186417 1.765038889
14.94294571 56.63267787 1.661855694
14.08079768 55.8835409 1.572365695
13.07503267 55.85394699 1.526148195
13.87707642 56.84325494 1.201778611
14.74834811 56.4797057 2.201030833
14.71780758 56.2190903 1.312630416
14.84688074 56.20134805 1.064184305
13.9756613 56.83511828 1.106081945
13.37482084 56.32555295 1.955326527
13.28496775 55.80313232 1.281214445
13.48814841 55.50025435 1.612392361
13.33917893 56.02853829 1.843289861
13.78947363 55.99783619 1.712659583
13.94116263 56.3137174 1.441294722
12.94495248 55.89677924 1.427171389
13.93984079 56.9426305 1.49043875
15.12394257 57.14469774 1.834394167
13.43537424 56.82053079 1.990671805
14.3348616 55.98401349 1.42602875
15.07312973 56.51587606 1.730443055
13.06228068 55.46729248 1.334419722
15.09067168 57.05489271 1.720642222
15.3000038 56.43467672 2.145260556
14.42783245 56.2001194 1.928752916
12.62154803 56.21451481 1.284935278
14.5647095 56.91941521 1.203295972
12.82352863 56.06545274 1.310144583
15.12128092 56.32716729 1.653416527
15.41977285 57.00032105 1.830578333
13.0108648 56.48199917 1.334979166
13.79627271 56.29442363 1.608296806
13.69390585 55.9788893 1.636546111
13.85415898 56.51959889 1.940849583
13.42994326 56.16451808 1.556413611
13.94165947 56.29575144 1.459196945
13.63833274 55.73566343 1.742808889
13.78097707 56.26731808 1.453552362
'''
df_centroid_Coord = pd.read_csv(StringIO(data), delim_whitespace=True)
data = '''
ID "Ambulance station name" Longtitude Latitude
0 1 AImhult 14.128734 56.547992
1 2 Angelhdm 12.870739 56.242114
2 3 Alvesta 14.549503 56.920740
3 4 "Ostra Ljungby" 13.057450 56.188099
4 5 Broby 14.080958 56.254481
5 6 Bromölla 14.466869 56.072272
6 7 Försláv 12.814913 56.350098
7 9 Hasslehdm 13.778234 56.161536
8 10 Haganas 12.556995 56.206016
9 11 Hörby 13.643265 55.849811
10 12 "Halmstad.Vaster" 12.819960 56.674306
'''
df_station = pd.read_csv(StringIO(data), delim_whitespace=True)
df_station.rename(columns={'Longtitude':'x', 'Latitude':'y'}, inplace=True)
df_centroid_Coord['Ambulance_Treatment_Time'] = df_centroid_Coord ['Base_TT']
fig = px.scatter(df_centroid_Coord, x="x", y="y",
title="Southern Region Centroids",
color='Ambulance_Treatment_Time',
log_x=True,
size_max=60,
color_continuous_scale='Reds',
range_color=(0.5,2),
)
fig.update_traces(marker={'size': 4, 'symbol': 1})
fig.add_trace(go.Scatter(x=df_station['x'],
y=df_station['y'],
mode='markers+text',
text=df_station['Ambulance station name'],
textposition='top center',
showlegend=True,
marker=dict(
size=8,
symbol=2,
color='black'
)
)
)
fig.show()
If I read the same data from externals files, it does not work. Like
if I plot the data of map coordniates (from Excel file) and then
plot ambulance data (from Excel file), ambulance symbol in the
diamond shape appears behind the map. It is not showing on the front.
When dataset inside the code, the ambulance data is shown and not hidden
Increased ambulance size - When dataset inside the code, the ambulance data is shown and not hidden
I think that there is no problem, I tried the same code with 2 Excel files with your data and I got the plot below:
import plotly.express as px
import plotly.graph_objects as go
from openpyxl import load_workbook
import pandas as pd
import numpy as np
import io
file_loc_1 = "AgeGroupData_time_to_treatment.xlsx"
df_centroid_Coord = pd.read_excel(file_loc_1, index_col=None, na_values=['NA'])
df_centroid_Coord
file_loc2Amb = "Ambulance IDs.xlsx"
df_station = pd.read_excel(file_loc2Amb, index_col=None, na_values=['NA'], usecols="A:D")
df_station.rename(columns={'Longtitude':'x', 'Latitude':'y'}, inplace=True)
df_centroid_Coord['Ambulance_Treatment_Time'] = df_centroid_Coord ['Base_TT']
fig = px.scatter(df_centroid_Coord, x="x", y="y",
title="Southern Region Centroids",
color='Ambulance_Treatment_Time',
log_x=True,
size_max=60,
color_continuous_scale='Reds',
range_color=(0.5,2),
)
fig.update_traces(marker={'size': 4, 'symbol': 1})
fig.add_trace(go.Scatter(x=df_station['x'],
y=df_station['y'],
mode='markers+text',
text=df_station['Ambulance station name'],
textposition='top center',
showlegend=True,
marker=dict(
size=12,
symbol=2,
color='black'
)
)
)
fig.update_layout(width=1000, height=800, paper_bgcolor="LightSteelBlue")
fig.show()
I am currently viewing the neighborhoods. However, when I hover the mouse over it, I want a text to be displayed with the neighborhood and the average price. I have pasted my code and my card what I made. Below you can see how I would like it.
How can I display a text when I hover over it?
import folium
from folium.plugins import FastMarkerCluster
from branca.colormap import LinearColormap
map_ams_price = folium.Map(location=[52.3680, 4.9036], zoom_start=11, tiles="cartodbpositron")
map_ams_price.choropleth(
geo_data=r'C:\neighbourhoods.geojson',
data=df,
columns=['neighbourhood_cleansed', 'price'],
key_on='feature.properties.neighbourhood',
fill_color='BuPu',
fill_opacity=0.7,
line_opacity=0.2,
legend_name='Avg',
reset=True,
tooltip=folium.features.GeoJsonTooltip(fields=['neighbourhood_cleansed', 'price'],
labels=True,
sticky=False),
)
map_ams_price
Minium Example
# the price is the avg price
d = {'neighbourhood_cleansed': ['Oostelijk Havengebied - Indische Buurt', 'Centrum-Oost',
'Centrum-West', 'Zuid', 'De Baarsjes - Oud-West', 'Bos en Lommer',
'De Pijp - Rivierenbuurt', 'Oud-Oost', 'Noord-West', 'Westerpark',
'Slotervaart', 'Oud-Noord', 'Watergraafsmeer',
'IJburg - Zeeburgereiland', 'Noord-Oost', 'Buitenveldert - Zuidas',
'Geuzenveld - Slotermeer', 'De Aker - Nieuw Sloten', 'Osdorp',
'Bijlmer-Centrum', 'Gaasperdam - Driemond', 'Bijlmer-Oost'],
'price': [20.0,30.0,40.0,50.0,60.0,70.0,80.0,20.0,30.0,40.0,50.0,60.0,70.0,80.0,20.0,30.0,40.0,50.0,60.0,70.0,80.0,20.0]}
df = pd.DataFrame(data=d)
You can find the geojson here https://pastecode.io/s/a76fdvey
As I mentioned in the comments, in order to give tooltips in the choropleth map, they have to be in the geojson file, not in the dataframe value, in order to be displayed. So I used geopandas for the geojson file to be used, combined the data frames and added the price information to the geojson file. The column names in the original data frame have been modified to match the geojson file. It can also be used as a label by adding an alias name. The tooltip can be styled, so I added that as well.
import json
import requests
import geopandas as gpd
url = "http://data.insideairbnb.com/the-netherlands/north-holland/amsterdam/2021-09-07/visualisations/neighbourhoods.geojson"
gpd_geo = gpd.read_file(url)
gpd_geo = gpd_geo.merge(df, on='neighbourhood')
geo_json_data = gpd_geo.to_json()
import folium
from folium.plugins import FastMarkerCluster
from branca.colormap import LinearColormap
from folium.features import GeoJsonPopup, GeoJsonTooltip
map_ams_price = folium.Map(location=[52.3680, 4.9036], zoom_start=11, tiles="cartodbpositron")
choropleth = folium.Choropleth(
geo_data=geo_json_data,
data=df,
columns=['neighbourhood', 'price'],
key_on='feature.properties.neighbourhood',
fill_color='BuPu',
fill_opacity=0.7,
line_opacity=0.2,
legend_name='Avg',
reset=True,
highlight=True,
).add_to(map_ams_price)
choropleth.geojson.add_child(
folium.features.GeoJsonTooltip(fields=['neighbourhood', 'price'],
aliases=['neighbourhood:', 'average_price:'],
labels=True,
localize=True,
sticky=False,
style="""
background-color: #F0EFEF;
border: 2px solid black;
border-radius: 3px;
box-shadow: 3px;
""",)
)
map_ams_price
I have linked the data and chosen the right parameters, but the map is empty. I have also looked at the documentation of https://plotly.com/python/mapbox-county-choropleth/ , but that doesn't help me.
Here is the code I made:
# IMPORTEREN VAN LIBARIES
import plotly.express as px
import pandas as pd
import plotly
import plotly.offline as po
from urllib.request import urlopen
import json
# LEZEN VAN DATASET
fietsdata = pd.read_excel('Fietsdata.xlsx')
with urlopen('http://larscuny.info/projecten/dip/data/countries.json') as response:
countries = json.load(response)
fig = px.choropleth_mapbox(
fietsdata,
geojson=countries,
locations='country',
color='total_profit',
color_continuous_scale="Viridis",
mapbox_style="open-street-map", # carto-positron
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
# LAYOUT VAN DE VISUALISATIE
fig.update_layout(
font_family="Poppins",
font_color="#002072",
title_font_family="Poppins",
title_font_color="#002072",
legend_title="Gender",
legend_title_font_color="#002072",
)
# OPEN VISUALISATIE
po.plot(fig, filename="total-revenue.html")
And the dataset I used:
country
state
total_costs
total_revenue
total_profit
Canada
Brittish Columbia
360.00
950.00
590.00
Australia
New South Wales
1,035.00
2,401.00
1366.00
United States
Oregon
405.00
929.00
524.00
I hope someone can help me
your data preparation does not consider that country is not in the geojson as a property. Have used geopandas for prep and joining. NB - USA is lost as join keys are inconsistent
you should consider where you want to be the center and the zoom level
# IMPORTEREN VAN LIBARIES
import plotly.express as px
import pandas as pd
import geopandas as gpd
import plotly
import plotly.offline as po
from urllib.request import urlopen
import json
# LEZEN VAN DATASET
# fietsdata = pd.read_excel('Fietsdata.xlsx')
fietsdata =pd.DataFrame({'country': ['Canada', 'Australia', 'United States'],
'state': ['Brittish Columbia', 'New South Wales', 'Oregon'],
'total_costs': ['360.00', '1,035.00', '405.00'],
'total_revenue': ['950.00', '2,401.00', '929.00'],
'total_profit': [590.0, 1366.0, 524.0]})
with urlopen('http://larscuny.info/projecten/dip/data/countries.json') as response:
countries = json.load(response)
# use geopandas and join data together
gdf = gpd.GeoDataFrame.from_features(countries)
gdf = gdf.merge(fietsdata, left_on="ADMIN", right_on="country")
fig = px.choropleth_mapbox(
gdf,
geojson=gdf.geometry,
locations=gdf.index,
color='total_profit',
color_continuous_scale="Viridis",
center={"lat": gdf.iloc[0].geometry.centroid.y, "lon": gdf.iloc[0].geometry.centroid.x},
zoom=1,
mapbox_style="open-street-map", # carto-positron
)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
# LAYOUT VAN DE VISUALISATIE
fig.update_layout(
font_family="Poppins",
font_color="#002072",
title_font_family="Poppins",
title_font_color="#002072",
legend_title="Gender",
legend_title_font_color="#002072",
)
# OPEN VISUALISATIE
fig
I'm trying to display a Plotly Choropleth Map in Jupyter Notebooks (I'm a beginner with this type of stuff) and for some reason it won't display correctly.
The csv file I am using for it can be found here:
https://www.kaggle.com/ajaypalsinghlo/world-happiness-report-2021
Here is the code leading up to the choropleth:
# here we're assigning the hover data columns to use for our choropleth map below
hover_data_cols_df = ['Country', 'Life Ladder', 'Log GDP per capita', 'Social support', 'Healthy life expectancy at birth', 'Freedom to make life choices', 'Generosity', 'Perceptions of corruption']
df.groupby('Year').Country.count()
and here is the code for the actual choropleth:
choropleth_map = px.choropleth(df,
locations="Country",
color='Life Ladder',
hover_name = 'Life Ladder',
hover_data = hover_data_cols_df,
color_continuous_scale = px.colors.sequential.Oranges,
animation_frame="Year"
).update_layout (title_text = 'World Happiness Index - year wise data', title_x = 0.5,);
iplot(choropleth_map)
I'm not getting any error messages attached to it currently, however when I check my console log on my browser, I do find this error:
Wolrd-Happiness-Report.ipynb:1 Uncaught ReferenceError: require is not defined
at <anonymous>:1:17
at t.attachWidget (jlab_core.64abc115a1efeec58694.js?v=64abc115a1efeec58694:2)
at t.insertWidget (jlab_core.64abc115a1efeec58694.js?v=64abc115a1efeec58694:2)
at x._insertOutput (jlab_core.64abc115a1efeec58694.js?v=64abc115a1efeec58694:2)
at x.onModelChanged (jlab_core.64abc115a1efeec58694.js?v=64abc115a1efeec58694:2)
at m (jlab_core.64abc115a1efeec58694.js?v=64abc115a1efeec58694:2)
at Object.l [as emit] (jlab_core.64abc115a1efeec58694.js?v=64abc115a1efeec58694:2)
at e.emit (jlab_core.64abc115a1efeec58694.js?v=64abc115a1efeec58694:2)
at c._onListChanged (jlab_core.64abc115a1efeec58694.js?v=64abc115a1efeec58694:2)
at m (jlab_core.64abc115a1efeec58694.js?v=64abc115a1efeec58694:2)
I'm not too sure if this is related or not!
Thanks all!
Your task requires a setting that associates a country name with a country on the map. It requires that the location mode be the country name.
import pandas as pd
df = pd.read_csv('./data/world-happiness-report.csv', sep=',')
df.sort_values('year', ascending=True, inplace=True)
hover_data_cols_df = ['Country name', 'year', 'Life Ladder', 'Log GDP per capita', 'Social support', 'Healthy life expectancy at birth', 'Freedom to make life choices', 'Generosity', 'Perceptions of corruption']
import plotly.express as px
fig = px.choropleth(df,
locations="Country name",
locationmode='country names',
color='Life Ladder',
hover_name = 'Life Ladder',
hover_data = hover_data_cols_df,
color_continuous_scale = px.colors.sequential.Oranges,
animation_frame="year"
)
fig.update_layout (title_text = 'World Happiness Index - year wise data', title_x = 0.5,);
fig.show()