def update_map(input_race, input_region, input_sex, input_state): # https://plotly.com/python/builtin-colorscales/ df_local = filter_data( df=df_map, input_race=input_race, input_sex=input_sex, input_state=input_state, input_region = input_region ) df_local = df_local.groupby(['State', 'Region', 'State Code']).sum().reset_index() df_local["Executions scaled"] = np.log(df_local["Executions"]) fig = go.Figure( data=go.Choropleth( locations=df_local['State Code'], z=df_local["Executions scaled"].astype(float), zmin=0, zmax=8, locationmode='USA-states', colorscale=px.colors.sequential.Teal, colorbar_len=0.5, autocolorscale=False, marker_line_color='white', # line markers between states text=df_local[['State', 'Executions', 'White Convicted', 'Other Convicted']], # hover text hovertemplate= '<b>%{text[0]}</b><br>' + '<i>Executions</i>: %{text[1]} <br>' + '<extra></extra>', colorbar=dict( title="No. of executions", x=0.9, y=0.5, titleside="top", tickmode="array", tickvals=[0.5, 7.5], ticktext=['Low', 'High'], ticks="outside" ) )) fig.update_layout( # title_text='Death Row Executions 1977-2020', geo = dict( scope='usa', projection=go.layout.geo.Projection(type = 'albers usa'), showlakes=True, lakecolor='rgb(255, 255, 255)' ), height=600, width=1300, hoverlabel=dict( bgcolor="white", font_size=16, font_family="Rockwell" ), hoverlabel_align = 'right', margin = dict(t=0, l=0, r=0, b=50), legend=dict( bgcolor='black', orientation='v' ) ) return fig
'VA': 8.5, 'WA': 9.6, 'WV': 12.3, 'WI': 9.0, 'WY': 8.7 } # Compile data into two lists codes = list(asthma_data.keys()) percents = list(asthma_data.values()) # Create map fig = go.Figure(data=go.Choropleth( locations=codes, # Spatial coordinates z=percents, # Data to be color-coded locationmode='USA-states', # set of locations match entries in `locations` colorscale='Reds', colorbar_title="Population diagnosed with asthma (%)", )) # Metadata fig.update_layout( title_text='Asthma frequency by state', geo_scope='usa', # limite map scope to USA ) def get_html(): return fig.to_html()
def set_plot(date, plotType, type): if type == 'individual_date': confirmed_viz = confirmed_1.copy(deep=True) confirmed_viz['text'] = confirmed_viz['Country'].astype(str) + '(' + 'code:' + confirmed_viz['CODE'].astype(str)+ ')' + '<br>' \ 'count: ' + confirmed_viz[date].astype(str) trace = go.Choropleth( locations=confirmed_viz['CODE'], z=confirmed_viz[date], text=confirmed_viz['Country'], autocolorscale=False, colorscale="redor", marker={'line': { 'color': 'rgb(180,180,180)', 'width': 0.5 }}, colorbar={ "thickness": 10, "len": 0.7, "x": 1.3, "y": 0.4, 'title': { "text": "Confirmed cases", "side": "top" } }) fig = { "data": [trace], "layout": go.Layout(title="Corona cases - " + str(date), plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], font={'color': colors['text']}, autosize=True, hovermode='closest', margin=dict(t=-0, b=0, l=0, r=0), geo={ 'bgcolor': 'rgba(0,0,0,0)', 'showframe': True, 'showcoastlines': True, 'oceancolor': 'aqua', 'showocean': True, 'projection': { 'type': plotType } }) } if type == 'continuous_growth': confirmed_viz = confirmed_2.copy(deep=True) confirmed_viz['text'] = confirmed_viz['Country'].astype(str) + '(' + 'code:' + confirmed_viz['CODE'].astype(str)+ ')' + '<br>' \ 'count: ' + confirmed_viz[date].astype(str) trace = go.Choropleth( locations=confirmed_viz['CODE'], z=confirmed_viz[date], text=confirmed_viz['Country'], autocolorscale=False, colorscale="redor", marker={'line': { 'color': 'rgb(180,180,180)', 'width': 0.5 }}, colorbar={ "thickness": 10, "len": 0.7, "x": 1.3, "y": 0.4, 'title': { "text": "Confirmed cases", "side": "top" } }) fig = { "data": [trace], "layout": go.Layout(title="Corona cases - " + str(date), plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], font={'color': colors['text']}, autosize=True, hovermode='closest', margin=dict(t=-0, b=0, l=0, r=0), geo={ 'bgcolor': 'rgba(0,0,0,0)', 'showframe': True, 'showcoastlines': True, 'oceancolor': 'aqua', 'showocean': True, 'projection': { 'type': plotType } }) } return fig
# Merge percent world emissions and percent world population df = df_em_2017_codes[['country', 'code', 'percent_emissions']].merge(df_po_2017_adj[['code', 'percent_population']]) # Create new column for 'score' and 'rounded_score' df['score'] = df['percent_emissions'] / df['percent_population'] df['rounded_score'] = round(df['score'], 0) import plotly.graph_objects as go import plotly.express as px fig = go.Figure(data=go.Choropleth( locations=df['code'], # Spatial coordinates z = df['score'].astype(float), # Data to be color-coded text = df['country'], colorscale = px.colors.sequential.Viridis, zmax = 4.0, zmin = 0.0, marker_line_color='darkgray', marker_line_width=0.5, )) fig.update_layout( title_text='proportion of global CO2 emissions vs proportion of the global population', geo=dict( showframe=False, showcoastlines=False, projection_type='equirectangular' ), ) fig.show()
import plotly.graph_objects as go import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv') fig = go.Figure(data=go.Choropleth( locations = df['CODE'], z = df['GDP (BILLIONS)'], text = df['COUNTRY'], colorscale = 'Blues', autocolorscale=False, reversescale=True, marker_line_color='darkgray', marker_line_width=0.5, colorbar_tickprefix = '$', colorbar_title = 'GDP<br>Billions US$', )) fig.update_layout( title_text='2014 Global GDP', geo=dict( showframe=False, showcoastlines=False, projection_type='equirectangular' ), annotations = [dict( x=0.55, y=0.1, xref='paper', yref='paper', text='Source: <a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">\
df1[col] = df1[col].astype(str) # displaying the details df1['text'] = df1['Country_Region'] + '<br>' + \ 'Confirmed: ' + df1['Confirmed'] +'<br>'\ 'Recovered: ' + df1['Recovered'] + '<br>' + \ 'Deaths: ' +df1['Deaths'] + '<br>' + \ 'Active: ' +df1['Active'] fig = go.Figure(data=go.Choropleth( locations = df1['iso_alpha'], z = df1['Confirmed'], text = df1['text'], colorscale = 'Blues', autocolorscale=False, reversescale=True, marker_line_color='darkgray', marker_line_width=0.5, colorbar_tickprefix = '', colorbar_title = 'No. of Cases', )) fig.update_layout( title_text='COVID 19', geo=dict( showframe=False, showcoastlines=False, projection_type='equirectangular' ), annotations = [dict( x=0.55,
def renderGraphPage(): #print("Preprocessing data....") #print("Please wait....") alldata = [] parentDir = os.pardir # #directory = os.getcwd()+'/dataset/' #dataset directory directory = os.getcwd() + '/../data/ATP_Matches/' #dataset directory for filename in os.listdir(directory): if filename.endswith(".csv") and filename.startswith("atp"): #print(os.path.join(directory, filename)) year = filename.split("_")[2].split( "." )[0] #Getting year from filename to add in dataframe in Year column file1 = open(os.path.join(directory, filename), 'r') Lines = file1.readlines() file_list = [] for line in Lines: list_lin = line.rstrip("\n").rstrip(',').split( ",") #Stripping out additional comma at the end of line file_list.append( list_lin) #appending cleaned lies to a temp list tempdf = pd.DataFrame( file_list[1:], columns=file_list[0] ) #converting temp list (excluding first line as headings) into dataframe tempdf['year'] = int(year) #Adding year into dataframe columns alldata.append(tempdf) #adding dataframe to a list else: continue tennis_df = pd.concat(alldata) #Concatenating all data frame tennis_df.reset_index(drop=True, inplace=True) #Resetting index # # Countries df for creating map # In[3]: countries_df = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv' ) countries_df['new_name'] = countries_df['COUNTRY'].str.upper().apply( lambda y: y[0:3]) # In[4]: countries_df[countries_df['COUNTRY'].str.contains("Ne")] # # Winner Count per country per year # In[5]: winning_country_year_df = [ ] #We will have seperate dataframe for every year, all dataframe to be stored in this list year_key = {} count = 0 for year in set(list(tennis_df['year'])): #Looping through countries tmp_list = [] for country in set( list(tennis_df[tennis_df['year'] == year] ['winner_ioc'])): #Looping through years if country != None: tmp_list.append([ country, len(tennis_df[(tennis_df['winner_ioc'] == country) & (tennis_df['year'] == year)]) ]) #Addding country name and number of winners winning_country_year_df.append( pd.DataFrame(tmp_list, columns=[ 'Country', 'Winner_Count' ])) #converting to a dataframe and storing to list year_key[ count] = year #Creating index to year dictionary for future reference count += 1 # In[6]: winning_country_year_geometry_df = [ ] #List to hold dataframe for every year. Each dataframe will be an extension of world df with winner count as additional column #Below are some hard coded values to map with the ones in world dataframe # unavailable_Country_codes = [ ] #To save country codes which are not available #AHO belong to netherlands antilles, which is not available in world dataframe hence mapping it to USA #Dictionary to map ATP country code to ISO country code for the ones which are tricky some_known_dict = { 'INA': 'IDN', 'PUR': 'PRI', 'ESA': 'EST', 'RSA': 'ZAF', 'MAS': 'MYS', 'NED': 'NLD', 'TPE': 'TWN', 'SUI': 'CHE', 'CRC': 'CRI', 'IRI': 'IRN', 'UAE': 'ARE', 'NGR': 'NGA' } some_known_dict_ambigous = {'AHO': 'USA'} #df['CODE'] for e in range(len(winning_country_year_df)): geom_col = [ ] #We want to create a new column which will have the iso_a3 country code for a given country for each_count in list(winning_country_year_df[e] ['Country']): #each_count is each_country subsetdf = countries_df[ countries_df['CODE'] == each_count] #Checking is the ATP country code is same as iso country code if len(subsetdf) == 1: geom_col.append( subsetdf.iloc[0]['CODE']) #Appending the iso country code else: subsetdf = countries_df[ countries_df['new_name'] == each_count] #We created a new columns with the first 3 letters of every country. Checking to see if it matches ATP code if len(subsetdf) > 0: geom_col.append( subsetdf.iloc[0]['CODE'] ) #In case of a match, Appending its iso country code else: try: subsetdf = countries_df[ countries_df['CODE'] == some_known_dict[ each_count]] #Else checking in out dictonary for the ATP country code if len(subsetdf) > 0: geom_col.append( some_known_dict[each_count] ) #In case of a match appending its iso_a3 country code else: #print(each_count," could not be found") #Else printing to check manually unavailable_Country_codes.append(each_count) #print(e) geom_col.append("") except: #Else printing to check manually #print(each_count," could not be found") unavailable_Country_codes.append(each_count) #print(e) geom_col.append("") winning_country_year_df[e][ 'matching_col'] = geom_col #Appending the new column to the dataframe tmp_world_df = countries_df.merge(winning_country_year_df[e], how='left', left_on="CODE", right_on="matching_col") tmp_world_df['Winner_Count'] = tmp_world_df['Winner_Count'].fillna(0) winning_country_year_geometry_df.append(tmp_world_df) unavailable_Country_codes = set(unavailable_Country_codes) #if len(unavailable_Country_codes) > 0: #print("Unavailable country codes",unavailable_Country_codes) # # Loser Count Per Country # In[7]: losing_country_year_df = [ ] #We will have seperate dataframe for every year, all dataframe to be stored in this list for year in set(list(tennis_df['year'])): #Looping through countries tmp_list = [] for country in set( list(tennis_df[tennis_df['year'] == year] ['loser_ioc'])): #Looping through years if country != None: tmp_list.append([ country, len(tennis_df[(tennis_df['loser_ioc'] == country) & (tennis_df['year'] == year)]) ]) #Addding country name and number of winners losing_country_year_df.append( pd.DataFrame(tmp_list, columns=[ 'Country', 'Loser_Count' ])) #converting to a dataframe and storing to list losing_country_year_geometry_df = [ ] #List to hold dataframe for every year. Each dataframe will be an extension of world df with winner count as additional column #Below are some hard coded values to map with the ones in world dataframe # unavailable_Country_codes = [ ] #To save country codes which are not available #AHO belong to netherlands antilles, which is not available in world dataframe hence mapping it to USA #Dictionary to map ATP country code to ISO country code for the ones which are tricky some_known_dict = { 'INA': 'IDN', 'PUR': 'PRI', 'ESA': 'EST', 'RSA': 'ZAF', 'MAS': 'MYS', 'NED': 'NLD', 'TPE': 'TWN', 'SUI': 'CHE', 'CRC': 'CRI', 'IRI': 'IRN', 'UAE': 'ARE', 'NGR': 'NGA' } some_known_dict_ambigous = {'AHO': 'USA'} #df['CODE'] for e in range(len(losing_country_year_df)): geom_col = [ ] #We want to create a new column which will have the iso_a3 country code for a given country for each_count in list(losing_country_year_df[e] ['Country']): #each_count is each_country subsetdf = countries_df[ countries_df['CODE'] == each_count] #Checking is the ATP country code is same as iso country code if len(subsetdf) == 1: geom_col.append( subsetdf.iloc[0]['CODE']) #Appending the iso country code else: subsetdf = countries_df[ countries_df['new_name'] == each_count] #We created a new columns with the first 3 letters of every country. Checking to see if it matches ATP code if len(subsetdf) > 0: geom_col.append( subsetdf.iloc[0]['CODE'] ) #In case of a match, Appending its iso country code else: try: subsetdf = countries_df[ countries_df['CODE'] == some_known_dict[ each_count]] #Else checking in out dictonary for the ATP country code if len(subsetdf) > 0: geom_col.append( some_known_dict[each_count] ) #In case of a match appending its iso_a3 country code else: #print(each_count," could not be found") #Else printing to check manually unavailable_Country_codes.append(each_count) #print(e) geom_col.append("") except: #Else printing to check manually #print(each_count," could not be found") unavailable_Country_codes.append(each_count) #print(e) geom_col.append("") losing_country_year_df[e][ 'matching_col'] = geom_col #Appending the new column to the dataframe tmp_world_df = countries_df.merge(losing_country_year_df[e], how='left', left_on="CODE", right_on="matching_col") tmp_world_df['Loser_Count'] = tmp_world_df['Loser_Count'].fillna(0) losing_country_year_geometry_df.append(tmp_world_df) unavailable_Country_codes = set(unavailable_Country_codes) #if len(unavailable_Country_codes) > 0: #print("Unavailable country codes",unavailable_Country_codes) # # Total players in a country # In[8]: country_dict = defaultdict(set) for k, g in tennis_df.groupby(["winner_name", "winner_ioc"]): country_dict[k[1]].add(k[0]) for k, g in tennis_df.groupby(["loser_name", "loser_ioc"]): country_dict[k[1]].add(k[0]) out = [[k, len(country_dict[k])] for k in country_dict] player_count = pd.DataFrame(out, columns=["country", "no_players"]) # # Winning Count - Normalised # In[9]: winning_country_year_norm_df = [ ] #We will have seperate dataframe for every year, all dataframe to be stored in this list for year in set(list(tennis_df['year'])): #Looping through countries tmp_list = [] country_dict = defaultdict(set) for k, g in tennis_df[tennis_df['year'] == year].groupby( ["winner_name", "winner_ioc"]): country_dict[k[1]].add(k[0]) out = [[k, len(country_dict[k])] for k in country_dict] winning_country_year_norm_df.append( pd.DataFrame(out, columns=["Country", "Winner_Count"])) for e in range(len(winning_country_year_norm_df)): for country in list(winning_country_year_norm_df[e]['Country']): winning_country_year_norm_df[e].loc[ winning_country_year_norm_df[e]['Country'] == country, 'Winner_Count'] /= np.array(player_count[ player_count['country'] == country]['no_players'])[0] #break #break # In[10]: winning_country_year_geometry_norm_df = [ ] #List to hold dataframe for every year. Each dataframe will be an extension of world df with winner count as additional column #Below are some hard coded values to map with the ones in world dataframe # unavailable_Country_codes = [ ] #To save country codes which are not available #AHO belong to netherlands antilles, which is not available in world dataframe hence mapping it to USA #Dictionary to map ATP country code to ISO country code for the ones which are tricky some_known_dict = { 'INA': 'IDN', 'PUR': 'PRI', 'ESA': 'EST', 'RSA': 'ZAF', 'MAS': 'MYS', 'NED': 'NLD', 'TPE': 'TWN', 'SUI': 'CHE', 'CRC': 'CRI', 'IRI': 'IRN', 'UAE': 'ARE', 'NGR': 'NGA' } some_known_dict_ambigous = {'AHO': 'USA'} #df['CODE'] for e in range(len(winning_country_year_norm_df)): geom_col = [ ] #We want to create a new column which will have the iso_a3 country code for a given country for each_count in list(winning_country_year_norm_df[e] ['Country']): #each_count is each_country subsetdf = countries_df[ countries_df['CODE'] == each_count] #Checking is the ATP country code is same as iso country code if len(subsetdf) == 1: geom_col.append( subsetdf.iloc[0]['CODE']) #Appending the iso country code else: subsetdf = countries_df[ countries_df['new_name'] == each_count] #We created a new columns with the first 3 letters of every country. Checking to see if it matches ATP code if len(subsetdf) > 0: geom_col.append( subsetdf.iloc[0]['CODE'] ) #In case of a match, Appending its iso country code else: try: subsetdf = countries_df[ countries_df['CODE'] == some_known_dict[ each_count]] #Else checking in out dictonary for the ATP country code if len(subsetdf) > 0: geom_col.append( some_known_dict[each_count] ) #In case of a match appending its iso_a3 country code else: #print(each_count," could not be found") #Else printing to check manually unavailable_Country_codes.append(each_count) #print(e) geom_col.append("") except: #Else printing to check manually #print(each_count," could not be found") unavailable_Country_codes.append(each_count) #print(e) geom_col.append("") winning_country_year_norm_df[e][ 'matching_col'] = geom_col #Appending the new column to the dataframe tmp_world_df = countries_df.merge(winning_country_year_norm_df[e], how='left', left_on="CODE", right_on="matching_col") tmp_world_df['Winner_Count'] = tmp_world_df['Winner_Count'].fillna(0) winning_country_year_geometry_norm_df.append(tmp_world_df) unavailable_Country_codes = set(unavailable_Country_codes) #if len(unavailable_Country_codes) > 0: #print("Unavailable country codes",unavailable_Country_codes) # # Losers Count - Normalised # In[11]: losing_country_year_norm_df = [ ] #We will have seperate dataframe for every year, all dataframe to be stored in this list for year in set(list(tennis_df['year'])): #Looping through countries tmp_list = [] country_dict = defaultdict(set) for k, g in tennis_df[tennis_df['year'] == year].groupby( ["loser_name", "loser_ioc"]): country_dict[k[1]].add(k[0]) out = [[k, len(country_dict[k])] for k in country_dict] losing_country_year_norm_df.append( pd.DataFrame(out, columns=["Country", "Loser_Count"])) for e in range(len(losing_country_year_norm_df)): for country in list(losing_country_year_norm_df[e]['Country']): losing_country_year_norm_df[e].loc[ losing_country_year_norm_df[e]['Country'] == country, 'Loser_Count'] /= np.array(player_count[ player_count['country'] == country]['no_players'])[0] #break #break # In[12]: losing_country_year_geometry_norm_df = [ ] #List to hold dataframe for every year. Each dataframe will be an extension of world df with winner count as additional column #Below are some hard coded values to map with the ones in world dataframe # unavailable_Country_codes = [ ] #To save country codes which are not available #AHO belong to netherlands antilles, which is not available in world dataframe hence mapping it to USA #Dictionary to map ATP country code to ISO country code for the ones which are tricky some_known_dict = { 'INA': 'IDN', 'PUR': 'PRI', 'ESA': 'EST', 'RSA': 'ZAF', 'MAS': 'MYS', 'NED': 'NLD', 'TPE': 'TWN', 'SUI': 'CHE', 'CRC': 'CRI', 'IRI': 'IRN', 'UAE': 'ARE', 'NGR': 'NGA' } some_known_dict_ambigous = {'AHO': 'USA'} #df['CODE'] for e in range(len(losing_country_year_norm_df)): geom_col = [ ] #We want to create a new column which will have the iso_a3 country code for a given country for each_count in list(losing_country_year_norm_df[e] ['Country']): #each_count is each_country subsetdf = countries_df[ countries_df['CODE'] == each_count] #Checking is the ATP country code is same as iso country code if len(subsetdf) == 1: geom_col.append( subsetdf.iloc[0]['CODE']) #Appending the iso country code else: subsetdf = countries_df[ countries_df['new_name'] == each_count] #We created a new columns with the first 3 letters of every country. Checking to see if it matches ATP code if len(subsetdf) > 0: geom_col.append( subsetdf.iloc[0]['CODE'] ) #In case of a match, Appending its iso country code else: try: subsetdf = countries_df[ countries_df['CODE'] == some_known_dict[ each_count]] #Else checking in out dictonary for the ATP country code if len(subsetdf) > 0: geom_col.append( some_known_dict[each_count] ) #In case of a match appending its iso_a3 country code else: #print(each_count," could not be found") #Else printing to check manually unavailable_Country_codes.append(each_count) #print(e) geom_col.append("") except: #Else printing to check manually #print(each_count," could not be found") unavailable_Country_codes.append(each_count) #print(e) geom_col.append("") losing_country_year_norm_df[e][ 'matching_col'] = geom_col #Appending the new column to the dataframe tmp_world_df = countries_df.merge(losing_country_year_norm_df[e], how='left', left_on="CODE", right_on="matching_col") tmp_world_df['Loser_Count'] = tmp_world_df['Loser_Count'].fillna(0) losing_country_year_geometry_norm_df.append(tmp_world_df) unavailable_Country_codes = set(unavailable_Country_codes) #if len(unavailable_Country_codes) > 0: #print("Unavailable country codes",unavailable_Country_codes) # # Default fig # In[13]: year_value = max(year_key.values()) reverse_year_key = {} for g in year_key.keys(): reverse_year_key[year_key[g]] = g def_fig = go.Figure(data=go.Choropleth( locations=winning_country_year_geometry_df[ reverse_year_key[year_value]]['CODE'], z=winning_country_year_geometry_df[ reverse_year_key[year_value]]['Winner_Count'], text=winning_country_year_geometry_df[reverse_year_key[year_value]] ['COUNTRY'], colorscale='Blues', autocolorscale=False, reversescale=False, marker_line_color='darkgray', marker_line_width=0.5, #colorbar_tickprefix = '$', colorbar_title='Winning macthes', )) def_fig.update_layout( title_text='Winners of ATP matches - ' + str(year_value), geo=dict(showframe=False, showcoastlines=False, projection_type='equirectangular'), ) # In[14]: app = dash.Dash(__name__, external_stylesheets=[dbc.themes.CERULEAN]) df = pd.read_csv( 'https://plotly.github.io/datasets/country_indicators.csv') #available_indicators = df['Indicator Name'].unique() app.layout = html.Div([ html.Div( [ dcc.Graph(id='winner_count', figure=def_fig), #dcc.Graph(id='y-time-series'), ], style={ 'display': 'inline-block', 'width': '100%' }), html.Div(dcc.Slider( id='crossfilter-year--slider', min=min(year_key.values()), max=max(year_key.values()), value=max(year_key.values()), marks={str(year): str(year) for year in set(year_key.values())}, included=False, step=None), style={ 'width': '100%', 'padding': '0px 20px 20px 20px' }), html.Div(dcc.Dropdown(id='type-dropdown', options=[{ 'label': 'Winning Matches', 'value': 'W1' }, { 'label': 'Losing Matches', 'value': 'L1' }, { 'label': 'Winners to Total players', 'value': 'W2' }, { 'label': 'Losers to Total players', 'value': 'L2' }], value='W1'), style={ 'width': '100%', 'padding': '0px 20px 20px 20px' }) ]) @app.callback(dash.dependencies.Output('winner_count', 'figure'), [ dash.dependencies.Input('crossfilter-year--slider', 'value'), dash.dependencies.Input('type-dropdown', 'value') ]) def update_figure(year_value, type_of_view): reverse_year_key = {} for g in year_key.keys(): reverse_year_key[year_key[g]] = g data_to_use = { 'W1': winning_country_year_geometry_df, 'L1': losing_country_year_geometry_df, 'W2': winning_country_year_geometry_norm_df, 'L2': losing_country_year_geometry_norm_df } color_bar_title_dict = { 'W1': 'Winning Matches', 'L1': 'Losing Matches', 'W2': 'Winners:Total ratio', 'L2': 'Losers:Total ratio' } fig_title_dict = { 'W1': 'Winning Matches of ATP', 'L1': 'Losing Matches of ATP', 'W2': 'Winners (to total players) of ATP', 'L2': 'Losers (to total players) of ATP' } key_to_use_dict = { 'W1': 'Winner_Count', 'L1': 'Loser_Count', 'W2': 'Winner_Count', 'L2': 'Loser_Count' } df_array_to_use = data_to_use[type_of_view] fig = go.Figure(data=go.Choropleth( locations=df_array_to_use[reverse_year_key[year_value]]['CODE'], z=df_array_to_use[reverse_year_key[year_value]][ key_to_use_dict[type_of_view]], text=df_array_to_use[reverse_year_key[year_value]]['COUNTRY'], colorscale='Blues', autocolorscale=False, reversescale=False, marker_line_color='darkgray', marker_line_width=0.5, #colorbar_tickprefix = '$', colorbar_title=color_bar_title_dict[type_of_view], )) fig.update_layout( title_text=fig_title_dict[type_of_view] + ' - ' + str(year_value), geo=dict(showframe=False, showcoastlines=False, projection_type='equirectangular'), ) return fig app.run_server(debug=True, use_reloader=True) #,port=8060)
def update_figure(cont): data = dataFrame[dataFrame.continent == cont] data_sorted = data.groupby(['location']).human_development_index.mean() HDI_per_country = pd.to_numeric(data_sorted.values, errors="coerce") # On prend l'age median pour chaque pays data_age_median = data[['iso_code', 'median_age', 'location']].groupby(by='location', as_index=False).agg(np.max) deaths_permillions = pd.to_numeric(data.groupby( ['location']).total_deaths_per_million.last().values, errors="coerce") extreme_poverty = pd.to_numeric(data.groupby( ['location']).extreme_poverty.last().values, errors="coerce") age_median = pd.to_numeric(data.groupby(['location' ]).median_age.last().values, errors="coerce") country = data_sorted.index.values.tolist() idx = [] for x in range(len(HDI_per_country)): if pd.isnull(HDI_per_country[x]) == True or pd.isnull( age_median[x]) or pd.isnull(extreme_poverty[x]): idx.append(x) HDI_per_country = np.delete(HDI_per_country, idx) country = np.delete(country, idx) deaths_permillions = np.delete(deaths_permillions, idx) age_median = np.delete(age_median, idx) extreme_poverty = np.delete(extreme_poverty, idx) fig1 = make_subplots() fig1.add_trace( go.Scatter(x=country, y=deaths_permillions, mode='markers', marker=dict(color=HDI_per_country, size=age_median, showscale=True, colorbar=dict(title="HDI"), colorscale="Bluered_r"))) fig1.update_layout(title='HDI', yaxis=dict(title="Décès par millions d'habitants"), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', title_font_color="white", font_color='white', legend_title_font_color='white', font=dict(size=14)) fig2 = go.Figure(data=go.Choropleth( locations=data_age_median['iso_code'], # Spatial coordinates z=data_age_median['median_age'].astype( float), # Data to be color-coded colorscale='Bluered_r', colorbar_title="Age Médian", )) if cont != "Oceania": fig2.update_layout( title_text='Age médian de la population', geo_scope="world" #cont.lower(), # limite map scope to USA ) fig2.update_layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', title_font_color="white", font_color='white', legend_title_font_color='white', font=dict(size=14)) fig2.update_geos(visible=False, showocean=True, oceancolor='lightblue') return fig1, fig2
temp_tots = [ df_eth['SP_ALZHDMTA'].sum() / num, df_eth['SP_OSTEOPRS'].sum() / num, df_eth['SP_CHRNKIDN'].sum() / num, df_eth['SP_CHF'].sum() / num, df_eth['SP_CNCR'].sum() / num, df_eth['SP_COPD'].sum() / num, df_eth['SP_DIABETES'].sum() / num, df_eth['SP_ISCHMCHT'].sum() / num, df_eth['SP_RA_OA'].sum() / num, df_eth['SP_STRKETIA'].sum() / num ] eth_totals.append(temp_tots) df_states_info[ 'text'] = 'Most Common Illness: ' + df_states_info['Most Common Illness'] fig = go.Figure(data=go.Choropleth( locations=df_states_info['State'], # Spatial coordinates z=df_states_info['Average_Chronic'].astype( float), # Data to be color-coded locationmode='USA-states', # set of locations match entries in `locations` colorscale='Reds', text=df_states_info['text'], # hover text colorbar_title="Average Chronic Illnesses", )) fig.update_layout( title_text= '2008 US Average # of Chronic Illnesses of patients with Depression', geo_scope='usa', # limite map scope to USA ) fig2 = go.Figure(data=[ go.Bar(name=ethns[0], x=chronics, y=eth_totals[0] * 100), go.Bar(name=ethns[1], x=chronics, y=eth_totals[1] * 100), go.Bar(name=ethns[2], x=chronics, y=eth_totals[2] * 100),
countries_latest_state['Log10Fatalities'] = np.log10( countries_latest_state.Fatalities + 1) countries_latest_state = countries_latest_state.sort_values(by='Fatalities', ascending=False) countries_latest_state.to_csv('countries_latest_state.csv', index=False) countries_latest_state.shape countries_latest_state.head() # %% [code] {"scrolled":false,"_kg_hide-input":true} fig = go.Figure(data=go.Choropleth( locations=countries_latest_state['country_iso_code_3'], z=countries_latest_state['Log10Confirmed'], text=countries_latest_state['Country_Region'], colorscale='viridis_r', autocolorscale=False, reversescale=False, marker_line_color='darkgray', marker_line_width=0.5, colorbar_tickprefix='10^', colorbar_title='Confirmed cases <br>(log10 scale)', )) _ = fig.update_layout( title_text=f'COVID-19 Global Cases [Updated: {TRAIN_END}]', geo=dict(showframe=False, showcoastlines=False, projection_type='equirectangular')) fig.show() # %% [code] {"_kg_hide-input":true}
US_data = [us_driving, us_walking, us_transit] Risk_data = [AZ_mobility, CA_mobility, FL_mobility, TX_mobility] fig1 = go.Figure(data=US_data) fig1.update_layout(title_text='Apple Maps Mobility Index', ) fig2 = go.Figure(data=Risk_data) fig2.update_layout(title_text='Apple Maps Mobility Driving States At-Risk', ) fig3 = go.Figure(data=go.Choropleth( locations=heat_map['State'], # Spatial coordinates z=heat_map['Mobility'], # Data to be color-coded locationmode='USA-states', # set of locations match entries in `locations` colorscale='Greens', colorbar_title="Mobility Index", )) fig3.update_layout( title_text='Apple Maps Mobility Heat Map', geo_scope='usa', # limite map scope to USA ) app = dash.Dash(__name__) app.layout = html.Div(children=[ html.H1(children=''), dcc.Graph(id='US Driving', figure=fig1), html.H2(children=''),
def update_graph(type): if type == 'Confirmed': dff = df_con.groupby('Country')['Confirmed'].max().reset_index() return { 'data': [ go.Choropleth(locations=dff['Country'], z=dff['Confirmed'], autocolorscale=False, locationmode='country names', colorscale='rainbow', marker={ 'line': { 'color': 'rgb(180,180,180)', 'width': 0.5 } }, colorbar={ 'thickness': 15, 'len': 1., 'x': 0.9, 'y': 0.7, 'title': { 'text': 'Confirmed', 'side': 'bottom' } }) ], 'layout': go.Layout( title= 'Confirmed cases all over the world, to see where exactly India stands' ) } elif type == 'Recovered': dff1 = df_con.groupby('Country')['Recovered'].max().reset_index() return { 'data': [ go.Choropleth(locations=dff1['Country'], z=dff1['Recovered'], autocolorscale=False, locationmode='country names', colorscale='rainbow', marker={ 'line': { 'color': 'rgb(255,255,255)', 'width': 0.5 } }, colorbar={ 'thickness': 15, 'len': 1, 'x': 0.9, 'y': 0.7, 'title': { 'text': 'Recovered', 'side': 'bottom' } }) ], 'layout': go.Layout( title= 'Recovered cases all over the world, to see where exactly India stands' ) } elif type == 'Deaths': dff2 = df_con.groupby('Country')['Deaths'].max().reset_index() return { 'data': [ go.Choropleth(locations=dff2['Country'], z=dff2['Deaths'], autocolorscale=False, locationmode='country names', colorscale='rainbow', marker={ 'line': { 'color': 'rgb(255,255,255)', 'width': 0.5 } }, colorbar={ 'thickness': 15, 'len': 1, 'x': 0.9, 'y': 0.7, 'title': { 'text': 'Deaths', 'side': 'bottom' } }) ], 'layout': go.Layout( title= 'Death cases all over the world,to see where exactly India stands' ) } else: return { 'data': [ go.Choropleth(locations=country5, z=test5, autocolorscale=False, locationmode='country names', colorscale='rainbow', marker={ 'line': { 'color': 'rgb(255,255,255)', 'width': 0.5 } }, colorbar={ 'thickness': 15, 'len': 1, 'x': 0.9, 'y': 0.7, 'title': { 'text': 'Total Tests', 'side': 'bottom' } }) ], 'layout': go.Layout( title= 'Total Tests all over the world,to see where exactly India stands' ) }
def plot_cancellation_by_state_and_month(df_cancel_stat): """ This function is to plot the dynamic cancellation map graph for different states in different months. :param df_cancel_stat: input cancellation data frame :type df_cancel_stat: pd.DataFrame :return: """ assert isinstance(df_cancel_stat, pd.DataFrame) fig = go.Figure( data=[ go.Choropleth( locations=df_cancel_stat[df_cancel_stat['month'] == constants.MONTH_LIST[0]] ['iso_region'].to_list(), z=df_cancel_stat[df_cancel_stat['month'] == constants.MONTH_LIST[0]]['count'].to_list(), locationmode='USA-states', colorscale='Portland', autocolorscale=False, marker_line_color='white', colorbar_title="Cancellation Rate", zmin=0, zmax=0.07) ], layout=go.Layout( title='2009 - 2018 January (01) US Airline Cancellation Rate', geo=dict( scope='usa', projection=go.layout.geo.Projection(type='albers usa'), showlakes=False, ), updatemenus=[ dict(type="buttons", buttons=[ dict(label="Play", method="animate", args=[None]), dict(label="Pause", method='animate', args=['', { 'mode': 'immediate' }]), ]) ], ), frames=[ go.Frame( data=[ go.Choropleth( locations=df_cancel_stat[df_cancel_stat['month'] == constants.MONTH_LIST[0]] ['iso_region'].to_list(), z=df_cancel_stat[df_cancel_stat['month'] == constants.MONTH_LIST[i]]['count'], locationmode='USA-states', colorscale='Portland', autocolorscale=False, marker_line_color='white', colorbar_title="Cancellation Rate", zmin=0, zmax=0.07) ], layout=go.Layout(title_text="2009 - 2018 " + constants.MONTH_ENG_LIST[i] + " (" + constants.MONTH_LIST[i] + ")" + " US Airline Cancellation Rate"), ) for i in range(12) ]) fig.show()
#https://www.youtube.com/watch?v=hSPmj7mK6ng youtube video ive been watching
import plotly.express as px import plotly.graph_objects as go from plotly.subplots import make_subplots state_code = {'Alabama': 'AL','Alaska': 'AK','Arizona': 'AZ','Arkansas': 'AR','California': 'CA','Colorado': 'CO','Connecticut': 'CT','Delaware': 'DE', 'Florida': 'FL','Georgia': 'GA','Hawaii': 'HI','Idaho': 'ID','Illinois': 'IL','Indiana': 'IN','Iowa': 'IA','Kansas': 'KS','Kentucky': 'KY', 'Louisiana': 'LA','Maine': 'ME','Maryland': 'MD','Massachusetts': 'MA','Michigan': 'MI','Minnesota': 'MN','Mississippi': 'MS','Missouri': 'MO', 'Montana': 'MT','Nebraska': 'NE','Nevada': 'NV','New Hampshire': 'NH','New Jersey': 'NJ','New Mexico': 'NM','New York': 'NY', 'North Carolina': 'NC','North Dakota': 'ND','Ohio': 'OH','Oklahoma': 'OK','Oregon': 'OR','Pennsylvania': 'PA','Rhode Island': 'RI', 'South Carolina': 'SC','South Dakota': 'SD','Tennessee': 'TN','Texas': 'TX','Utah': 'UT','Vermont': 'VT','Virginia': 'VA', 'District of Columbia': 'WA','Washington': 'WA','West Virginia': 'WV','Wisconsin': 'WI','Wyoming': 'WY'} sample['state_code'] = sample.State.apply(lambda x: state_code[x]) state_data = sample[['Sales', 'Profit', 'state_code']].groupby(['state_code']).sum() fig = go.Figure(data=go.Choropleth(locations=state_data.index, z = state_data.Sales, locationmode = 'USA-states', colorscale = 'blues', colorbar_title = 'Sales in USD')) fig.update_layout(title_text = 'Total State-Wise Sales',geo_scope='usa',height=600) fig.show() """Now, let us analyze the sales of a few random states from each profit bracket (high profit, medium profit, low profit, low loss and high loss) and try to observe some crucial trends which might help us in increasing the sales.""" def state_data_viewer(states): product_data = sample.groupby(['State']) for state in states: data = product_data.get_group(state).groupby(['Category']) fig, ax = plt.subplots(1, 3, figsize = (28,5)) fig.suptitle(state, fontsize=10) ax_index = 0 for category in ['Furniture', 'Office Supplies', 'Technology']:
df['country_code'] = df.country_code.apply(lambda x: country_name_to_country_alpha3(country_alpha2_to_country_name(x))) df['death rate']=(df['dead']/df['confirmed'])*100 df['recovery rate']=(df['recovered']/df['confirmed'])*100 st.sidebar.title("Filter country ") temp = df.to_dict('list') temp['location'] = list(set(temp['location'])) data = st.sidebar.selectbox("Select Country", temp['location']) st.subheader("NUMBER OF COVID 19 CASES AROUND THE WORLD") fig1 = go.Figure(data=go.Choropleth( locations = df['country_code'], z = df['confirmed'], text = df['location'], colorscale = 'Reds', autocolorscale=False, reversescale=False, marker_line_color='darkgray', marker_line_width=0.5, colorbar_tickprefix = '<>', colorbar_title = 'confirmed cases', )) fig1.update_layout( title_text='covid 19 confirmed cases', geo=dict( showframe=False, showcoastlines=False, projection_type='equirectangular' ), annotations = [dict( x=0.55, y=0.1,
data=go.Choropleth( geojson=os.path.join(data_dir, 'world.geo.json'), locations = map_df.ISO3, locationmode='geojson-id', z=map_df.carbonIntensity.astype(float), colorscale=myColors['map'], colorbar=dict( title=dict( # text="Carbon <br> intensity <br> (gCO2e/kWh)", font=dict( color=myColors['fontColor'], ) ), tickfont=dict( color=myColors['fontColor'], size=12, ), thicknessmode='fraction', thickness=0.04, xpad=3, ), showscale=True, hovertemplate="%{text} <extra> %{z:.0f} gCO2e/kWh </extra>", text=map_df.countryName, marker=dict( line=dict( color=myColors['boxesColor'], width=0.5 ) ), ),
covid_dat = pd.read_csv( 'https://covid.ourworldindata.org/data/owid-covid-data.csv') covid_dat # In[3]: tot_permil_630 = covid_dat[covid_dat['date'] == '2020-07-08'].reset_index( drop=True)[:-1] tot_permil_630['total_cases'] # In[4]: tot_permil_630 = covid_dat[covid_dat['date'] == '2020-07-08'].reset_index( drop=True)[:-1] fig = go.Figure(data=go.Choropleth( locations=tot_permil_630['iso_code'], z=tot_permil_630['total_cases'], text=tot_permil_630['location'], colorscale='RdBu', #autocolorscale=True, reversescale=True, marker_line_color='darkgray', marker_line_width=0.5, colorbar_title='Total cases', )) multiplier_fig_size = 0.75 fig.update_layout( title_text='Total cases at July 8, 2020', height=(800 * multiplier_fig_size), width=(1200 * multiplier_fig_size), geo=dict( showframe=False, #border of the globe map showcoastlines=True, #slightly thicker lines on shorelines projection_type='natural earth' #mercator projections ),
def pre_post_visual(cand, demo): '''This function returns a chloropleth maps that shows shift in pre/post election poll data for a given candidate(cand = 'Biden' or 'Trump') among the given demographic group ('Male', 'Female', 'White', 'Black', 'Hispanic/latino', 'White + BA/BS', 'White + No BA/BS', 'Republican', 'Democrat', 'Independent', '65+') ''' assert isinstance(cand, str) assert isinstance(demo, str) Prepoll = processing.avgPolls(processing.readPreElectionPolls(), ['Marist', 'Monmouth', 'Siena']) Postpoll = processing.readPostElectionPolls() dict_d = {} post, pre = [], [] # Extracting pre/post election poll data and the difference for particular demographic group. for i in Prepoll.index: if Prepoll.loc[i, 'Candidate'] == cand: for j in Postpoll.index: if Postpoll.loc[j, 'Candidate'] == cand and Prepoll.loc[ i, 'State'] == Postpoll.loc[j, 'State']: dict_d[Prepoll.loc[i, 'State']] = (Postpoll.loc[j, demo] - Prepoll.loc[i, demo]) * 100 pre.append(Prepoll.loc[i, demo] * 100) post.append(Postpoll.loc[j, demo] * 100) Diff = pd.DataFrame.from_dict(dict_d, orient='index', dtype=None, columns=['diff']) Diff['pre'] = pre Diff['post'] = post #creating cloumn for state IDs for spatial coordinates Abbv = pd.read_csv('data\state_abbrev.csv') Abbv.set_index('State', inplace=True) Code, ind = [], [] for i in Diff.index: if i in Abbv.index: Code.append(Abbv.loc[i, 'Code']) ind.append(i) Diff['State code'] = Code Diff['State'] = ind #converting to strings so that the data can be displayed when hovered over particular state. for col in Diff.columns: Diff[col] = Diff[col].astype(str) #text to be displayed when hovered over the map Diff['text'] = Diff['State']+ '<br>'+\ 'Prepolls ='+ Diff['pre']+'<br>'+\ 'Postpolls ='+ Diff['post'] fig = go.Figure(data=go.Choropleth( locations=Diff['State code'], # Spatial coordinates z=Diff['diff'], # Difference between post and pre poll data locationmode= 'USA-states', # set of locations match entries in `locations` colorscale='Fall', reversescale=True, zmid=0, text=Diff['text'], colorbar_title=("Percentage Difference"), colorbar=dict(tickfont=dict(size=12)), )) fig.update_layout( title_text="Shift in pre/post-election poll data among " + demo + " voters for " + cand, geo_scope='usa', # limite map scope to USA ) fig.update_layout(title_font_size=22) fig.show() return None
sex = 'Persons' group = 'DALYs 0-4' z = 'daly_norm_pm' ghe = 210 dalys = pandas.read_csv('DALYS.csv') select = dalys.query('sex == @sex') select = select.query('group == @group') select = select.query('GHE == @ghe') pio.renderers.default = "browser" fig = go.Figure(data=go.Choropleth( locations=select['country'], # Spatial coordinates z = (select[z]), # Data to be color-coded locationmode = "country names", # set of locations match entries in `locations` colorscale = 'hot', colorbar_title = "DALYs", )) fig.update_layout( title_text = 'Global burden of parasitic diseases: DALYs per million people aged 0-4', geo_scope='world', # limite map scope to USA ) fig.show() fig.write_image("fig1.pdf")
st.pyplot() elif columns == "Most sold products": plt.figure(figsize=(10, 6)) sns.barplot(x=best_seller_products.index, y=best_seller_products) plt.xticks(rotation=90) plt.show() st.pyplot() elif columns == "Number of customers by States": fig = go.Figure(data=go.Choropleth( locations=user_demo.state.value_counts().index, # Spatial coordinates z=user_demo.state.value_counts().values, # Data to be color-coded locationmode= 'USA-states', # set of locations match entries in `locations` colorscale='Reds', colorbar_title="Number of customers", )) fig.update_layout( title_text='Number of customers by State', geo_scope='usa', # limite map scope to USA ) st.plotly_chart(fig) elif columns == "Number of customer orders by States": fig = go.Figure(data=go.Choropleth( locations=order_user.state.value_counts().index, # Spatial coordinates
size = df_month['Value']/50, color = colors[i-6], line_width = 0 ))) df_sept = df.query('Month == 9') fig['data'][0].update(mode='markers+text', textposition='bottom center', text=df_sept['Value'].map('{:.0f}'.format).astype(str)+' '+\ df_sept['Country']) # Inset fig.add_trace(go.Choropleth( locationmode = 'country names', locations = df_sept['Country'], z = df_sept['Value'], text = df_sept['Country'], colorscale = [[0,'rgb(0, 0, 0)'],[1,'rgb(0, 0, 0)']], autocolorscale = False, showscale = False, geo = 'geo2' )) fig.add_trace(go.Scattergeo( lon = [21.0936], lat = [7.1881], text = ['Africa'], mode = 'text', showlegend = False, geo = 'geo2' )) fig.update_layout( title = go.layout.Title(
def page_1_dropdown(value): with open("Country lon and lat.csv") as ln: for line in ln: line = line.split(",") if(line[3].strip() in value): latitude = float(line[1]) longitude = float(line[2]) break eachfig = go.Figure(data=go.Choropleth( locations = df["Code"], # 標國家位置用三碼表示 text = df["text"], z = df["Cumulative_cases"], # 分佈數據 zauto=True, colorscale = "purpor", autocolorscale=False, reversescale=False, marker_line_color="darkgray", marker_line_width=0.5, #colorbar_title = "Confirmed Cases", )) eachfig.update_layout( geo=dict( showframe=False, showcoastlines=False, projection_type="equirectangular", ), ) eachfig.update_layout(geo=dict(bgcolor= "whitesmoke"), margin=dict(l=0, r=50, t=100, b=0,pad=0) ) eachfig.update_layout( title="<b>Confirmed Map<b>", titlefont=dict( size=22, color="#7f7f7f"), #設定標題名稱、字體大小、顏色 height=500, width=1000, ) eachfig.update_geos(center=dict(lon=longitude, lat=latitude), lataxis_range=[latitude-40,latitude+40], lonaxis_range=[longitude-40, longitude+40], ) cumulative = {} cumulativeDeath = {} with open("WHO-COVID-19-global-data.csv") as data: for line in data: line = line.split(",") if(line[2] == value): if(line[0] not in cumulative): cumulative[line[0]] = int(line[4]) if int(line[4]) > 0 else 0 cumulativeDeath[line[0]] = int(line[6]) if int(line[6]) > 0 else 0 else: cumulative[line[0]] += int(line[4]) if int(line[4]) > 0 else 0 cumulativeDeath[line[0]] += int(line[6]) if int(line[6]) > 0 else 0 cumulative = sorted(cumulative.items(), key=lambda x: datetime.strptime(x[0], "%Y-%m-%d")) cumulativeDeath = sorted(cumulativeDeath.items(), key=lambda x: datetime.strptime(x[0], "%Y-%m-%d")) date = [] total =[] totalDeathList = [] totalCases = 0 for i in range(len(cumulative)): date.append(cumulative[i][0]) total.append(cumulative[i][1]) totalCases += int(cumulative[i][1]) if int(cumulative[i][1]) > 0 else 0 totalDeathList.append(cumulativeDeath[i][1]) labels = ['Country Confirmed','World Confirmed'] values = [totalCases / world_total_confirmed, 1 - totalCases / world_total_confirmed] colors=["rgb(253,218,236)","#9467BD"] piefig = go.Figure(data=[go.Pie(labels=labels, values=values, hole=.50)]) piefig.update_traces(marker=dict(colors=colors)) piefig.update_layout(title='<b>Percent of confirmed cases<b>', titlefont=dict(size=22, color='#7f7f7f'), #設定標題名稱、字體大小、顏色 height=500 ), linefig = go.Figure( data=[ go.Scatter( x=date, y=total, mode="lines", line = dict(color = "purple"), fillcolor="blue", ) ], layout=go.Layout( title="<b>Daily New Cases<b>", titlefont=dict( size=22, color="#7f7f7f") ) ) linefig.update_traces(marker_line_colorscale="ylgn", showlegend=True, selector=dict(type="scatter"), name="New") linefig.update_layout(plot_bgcolor="whitesmoke") linefig.update_layout(modebar_bgcolor="black", margin=dict(l=20, r=50, t=100, b=50,pad=0)) lineDeathfig = go.Figure( data=[ go.Scatter( x=date, y=totalDeathList, mode="lines", line = dict(color = "purple"), fillcolor="blue", ) ], layout=go.Layout( title="<b>Daily Death Cases<b>", titlefont=dict(size=22, color="#7f7f7f" ) ) ) lineDeathfig.update_traces(marker_line_colorscale="ylgn", showlegend=True, selector=dict(type="scatter"), name="Death") lineDeathfig.update_layout(plot_bgcolor="whitesmoke") lineDeathfig.update_layout(modebar_bgcolor="black",margin=dict(l=20, r=50, t=100, b=50,pad=0)) return eachfig, piefig, linefig, lineDeathfig
import pandas as pd df = pd.read_csv( r'C:\Users\vivek\Documents\Code\local-items\30daychartchallenge-data\biodiverse-countries.csv' ) import plotly.graph_objects as go fig = go.Figure(data=go.Choropleth( locationmode="country names", locations=list(df.Country.values), #['Brazil', 'India'], z=list(df.Rank.values), text=list(df.Rank.values), autocolorscale=True, reversescale=False, colorbar_title='Biodiverse Rank', )) # Title fig.add_annotation( dict(xref='paper', yref='paper', x=0.5, y=1.22, xanchor='center', yanchor='top', font=dict(family='Arial', size=24, color='grey'), showarrow=False, text="Top 50 Most Biodiverse Countries")) # Subtitle fig.add_annotation( dict(xref='paper', yref='paper', x=0.5,
df['cc3'] = "???" df['text'] = "" countries = df.index.tolist() for i in countries: if df['duration'][i] > 0: df['qps'][i] = float(df['queries'][i]) / float(df['duration'][i]) if df['queries'][i] > 0: df['nxd'][i] = float(df['nx_domain'][i]) / float(df['queries'][i]) df['hom'][i] = float(df['home'][i]) / float(df['queries'][i]) df['cor'][i] = float(df['corp'][i]) / float(df['queries'][i]) df['mai'][i] = float(df['mail'][i]) / float(df['queries'][i]) df['cc3'][i] = m3summary.cc_to_iso3(df['cc'][i]) df['text'][i] = df['cc'][i] + '<br>' + 'duration ' + str(df['duration'][i]) + \ '<br>' + 'queries ' + str(df['queries'][i]) + \ '<br>' + 'nx ' + str(df['nx_domain'][i]) + \ '<br>' + 'home ' + str(df['home'][i]) + \ '<br>' + 'corp ' + str(df['corp'][i]) + \ '<br>' + 'mail ' + str(df['mail'][i]) print(df.head()) fig = go.Figure(data=go.Choropleth( locations=df['cc3'], z=df['mail'].astype(float), text=df['text'], # hover text marker_line_color='black', colorbar_title="Total queries")) fig.show()
for j in range(len(projections)): for i in range(len(datelist)): date = datelist[i] fig = go.Figure(data=[ go.Choropleth(locations=df['country_id'][usa], text=df['country_name'][usa], z=df[date][usa], zmin=0, zmax=nlabels, locationmode='USA-states', colorscale=colorscale, colorbar=dict(thickness=15, tickvals=tickvals, ticktext=ticktext), reversescale=False, marker_line_color='darkgray', marker_line_width=0.5, colorbar_tickprefix='', colorbar_title='Level'), go.Choropleth(locations=df['country_id'][world], text=df['country_name'][world], z=df[date][world], zmin=0, zmax=nlabels, locationmode='ISO-3', colorscale=colorscale, colorbar=dict(thickness=15,
def dead_zone_ratios_viz(df): index_cols = ['rec', 'country_code', 'elapsed_time', 'country'] map_df = df[index_cols] map_df.dropna(subset=['rec']) dead_zones_df = map_df[map_df['elapsed_time'].isna()] dead_zones_df['country_code'] = dead_zones_df['country'].str[:3].str.upper() write_csv(dead_zones_df, 'dead_zones_df.csv') dead_zones_counts = dead_zones_df.groupby(['country']).country_code.count() map_counts = map_df.groupby(['country']).country_code.count() dead_zones_dict = dead_zones_counts.to_dict() for country in map_counts.to_dict().keys(): if country not in dead_zones_counts.to_dict().keys(): print("country:", country) dead_zones_dict[country] = 1 dead_zones_counts = pd.Series(dead_zones_dict) map_df['count'] = map_df.groupby('country_code')['country_code'].transform('count') z_values = map_counts/dead_zones_counts c_codes_df = get_c_codes() c_unique = c_codes_df.drop_duplicates(subset=['country_code', "country"]) code_dict = {} for index, row in c_unique.iterrows(): country = row.country df_code = country[:3].upper() code_dict[df_code] = row.country_code dead_zones_df = dead_zones_df.rename(columns={"country_code": "code"}) dead_zones_df['code'] = dead_zones_df['code'].map(code_dict) fig = go.Figure(data=go.Choropleth( locations = dead_zones_df['code'], z = z_values, text = dead_zones_df['country'], colorscale = 'Reds', autocolorscale=False, reversescale=False, marker_line_color='darkgray', marker_line_width=0.5, colorbar_tickprefix = '', colorbar_title = 'Tor Dead Ratio', )) fig.update_layout( title_text='Tor Dead Zone Ratio', geo=dict( showframe=False, showcoastlines=False, projection_type='equirectangular' ), annotations = [dict( x=0.55, y=0.1, xref='paper', yref='paper', text='Tor: <a href="https://www.torproject.org/">\ The Tor Project</a>', showarrow = False )] ) return fig
'https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv' ) for col in df.columns: df[col] = df[col].astype(str) df['text'] = df['state'] + '<br>' + \ 'Beef ' + df['beef'] + ' Dairy ' + df['dairy'] + '<br>' + \ 'Fruits ' + df['total fruits'] + ' Veggies ' + df['total veggies'] + '<br>' + \ 'Wheat ' + df['wheat'] + ' Corn ' + df['corn'] fig = go.Figure(data=go.Choropleth( locations=df['code'], z=df['total exports'].astype(float), locationmode='USA-states', colorscale='Reds', autocolorscale=False, text=df['text'], # hover text marker_line_color='white', # line markers between states colorbar_title="Millions USD")) fig.update_layout( title_text='2011 US Agriculture Exports by State<br>(Hover for breakdown)', geo=dict( scope='usa', projection=go.layout.geo.Projection(type='albers usa'), showlakes=True, # lakes lakecolor='rgb(255, 255, 255)'), ) fig.show()
k=5, legend=True) ax.set_axis_off() ax.get_legend().set_bbox_to_anchor((.12, .12)) ax.get_figure() "Карта номер рас:" st.pyplot() with st.echo(code_location='below'): # idea from https://plotly.com/python/choropleth-maps/ fig = go.Figure(data=go.Choropleth(locations=country['CODE'], z=country[0], text=country['index'], colorscale="spectral", autocolorscale=False, reversescale=False, marker_line_color='darkgray', marker_line_width=0.5, colorbar_title='No.')) fig.update_layout(title_text='Nobel prizes per country', geo=dict(showframe=False, showcoastlines=False, projection_type='equirectangular'), annotations=[ dict(x=0.55, y=0.1, xref='paper', yref='paper', text="Можно туда сюда поводить потыкать",
# In[49]: app = dash.Dash(__name__, external_stylesheets=external_stylesheets) server = app.server # In[50]: fig = go.Figure(data=go.Choropleth( locations = df1['countryterritoryCode'], z = df1['cases'], text = df1['countriesAndTerritories'], colorscale = 'Reds', autocolorscale=False, marker_line_color='darkgray', marker_line_width=0.5, colorbar_title = 'Total Cases', )) # In[51]: fig.update_layout( geo=dict( showframe=False, showcoastlines=False, projection_type='equirectangular' ),