def create_plot(threshold: int = 0, rain: int = 0, dur: int = 0, green: bool = False, bm: bool = False, dens: bool = False, build: bool = False): green = 1 if green else 0 features = df[(df.threshold == float(threshold_marks[threshold])) & (df.rainfall == float(rainfall_marks[rain])) & (df.duration == float(duration_marks[dur])) & (df.green == green)] traces = list() traces.append( go.Choroplethmapbox(geojson=features.geometry.__geo_interface__, locations=features.index, z=features.threshold, showscale=False, colorscale=[[0, 'royalblue'], [1, 'royalblue']], marker=dict(opacity=0.5), hoverinfo='skip', below=below)) if build or dens: thresh = float(threshold_marks[threshold]) depth_column = 'max_depth_{}'.format(features.run_id.iloc[0]) buildings_above_threshold = building_depths[ building_depths[depth_column] >= thresh][[ depth_column, 'geometry', 'x', 'y' ]].rename(columns={depth_column: 'depth'}) if build: t = go.Choroplethmapbox( geojson=buildings_above_threshold.geometry.__geo_interface__, locations=buildings_above_threshold.index, z=buildings_above_threshold.depth, below=below, name='', hovertemplate='<b>%{z} m</b>') traces.append(t) if dens: traces.append( go.Densitymapbox(lat=buildings_above_threshold.y, lon=buildings_above_threshold.x, z=buildings_above_threshold.depth, radius=10, hoverinfo='skip', showscale=True if not build else False, below=below)) return go.Figure(traces, figure_layout.update(mapbox_style=bm))
def update_output(value): data = [] for e in value: if e == 'P': data.append('Score_PTS') elif e == 'PR': data.append('Score_PR') elif e == 'EST': data.append('Score_EST') title = get_title(data) title_size = title.pop() title = title.pop() colorscale = graph_color_scale() if len(data) > 0: z_value = get_z(df_scores, data) fig = go.Figure( go.Choroplethmapbox( geojson=json_scores, locations=df_scores.id, z=z_value, colorscale=colorscale, colorbar=dict(dtick=1), zmin=1, zmax=5, marker_opacity=(z_value / 10) + 0.4, marker_line_width=0, )) else: fig = go.Figure( go.Choroplethmapbox(geojson=json_scores, locations=df_scores.id, colorscale=colorscale)) fig.update_layout(title=dict(text=title, font=dict(size=title_size)), title_xref="paper", geo_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', paper_bgcolor='rgba(0,0,0,0)', height=550, mapbox_style="stamen-toner", autosize=True, mapbox_center={ "lat": 25.655624, "lon": -100.373121 }, mapbox_zoom=11) return dcc.Graph(figure=fig, style={'width': '90%'})
def mapa_updater(value_var): countries = mapas.countries df_mapas = consultas.df_mapa if value_var == 'N_Efectivas': labelgrap = "# efec" else: labelgrap = "Durac" for loc in countries['features']: loc['id'] = loc['properties']['NOMBRE_DPT'] trace_1 = go.Choroplethmapbox( geojson=countries, locations=df_mapas['dpto'], z=df_mapas[value_var], colorscale='ylgnbu', # zmin=0, zmax=12, marker_opacity=0.5, marker_line_width=0) layout = go.Layout(mapbox_style="carto-positron", height=700, width=550, mapbox_zoom=5, mapbox_center={ "lat": 4.570868, "lon": -74.2973328 }, margin={ "r": 0, "t": 0, "l": 0, "b": 0 }) fig = go.Figure(data=[trace_1], layout=layout) map_fig = [dcc.Graph(figure=fig, id='id_map')] return map_fig
def update_graph(day): dff = county_dfs[day] dff['FIPS'] = dff['FIPS'].map(lambda x: '0' + str(x) if (len(str(x)) <= 4) else str(x)) dff['County_'] = dff[usa_county_page_entities].map( lambda x: x if 'parish' in x.lower() else x + ' County') dff.loc[:, 'Text'] = [f'<b>{w}, <b>{y}</b><br>{int(x):,} Cases<br>{int(z):,} Deaths' for w, x, y, z in \ zip(dff['County_'], dff['Cases'], dff['Code'], dff['Deaths'])] return go.Figure(data=go.Choroplethmapbox( locations=dff['FIPS'], # Spatial coordinates geojson=counties, z=dff['Cases'].astype(float), # Data to be color-coded zmin=0, zmax=usa_county_page_df_grouped['Cases'].max() * 1.1, text=dff['Text'], hoverinfo='text', colorscale=[[0, "rgb(255, 250, 250)"], [0.0001, "rgb(255, 200, 170)"], [0.001, "rgb(255, 150, 120)"], [0.01, "rgb(255, 100, 70)"], [0.1, "rgb(255, 50, 20)"], [1.0, "rgb(100, 0, 0)"]], colorbar_title="Total Cases", marker_line_width=0)).update_layout( mapbox_style='white-bg', mapbox_zoom=2.5, mapbox_center={ "lat": 37.0902, "lon": -95.7129 }, geo_scope='usa', # limit map scope to USA, geo={'fitbounds': 'locations'}, title=dict(text='Total cases by county on ' + usa_county_page_dates[day], x=.5))
def create_layer(self): self.create_dataframe(self.states) self.map_india_layer = go.Figure( go.Choroplethmapbox( customdata=self.df, geojson=self.json_data, featureidkey=self.featureidkey, locations=self.df['states'], z=self.df['colors'], marker_opacity=0.5, )) self.map_india_layer.update_layout(mapbox_style="carto-positron", mapbox_zoom=3.4, mapbox_center={ "lat": 20.5937, "lon": 78.9629 }, height=550, width=1200, title='Sanitary Pads Machine App', title_font_size=20, margin_l=160, margin_r=0, margin_t=40, margin_b=0)
def create_map_fig(cls, query): with urlopen( 'https://raw.githubusercontent.com/PublicaMundi/MappingAPI/master/data/geojson/us-states.json' ) as response: states = json.load(response) df = DbHelper.query_db(query) df.columns = ['state', 'num_incidents'] state_names = df.state state_names = cls.clean_state_names(state_names) state_fips = [ us.states.lookup(state).fips for state in state_names if True ] df.state = state_fips fig = go.Figure( go.Choroplethmapbox(geojson=states, locations=df['state'], z=df['num_incidents'], colorscale="Viridis", zmin=df['num_incidents'].min(), zmax=df['num_incidents'].max(), marker_opacity=0.5, marker_line_width=0)) fig.update_layout(mapbox_style="carto-positron", mapbox_zoom=3, mapbox_center={ "lat": 37.0902, "lon": -95.7129 }) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) return fig
def update_national_total_cases_density(n): df = clean_daily_regional_data(get_regional_data_latestday()) return { 'data': [ go.Choroplethmapbox( geojson=geo_data, featureidkey="properties.COD_REG", locations=df["Region Id"], z=df["Total cases"] / df_pop_reg["Population"] * 2000, text=df['Region'], hovertemplate='<b>Region</b>: <b>%{text}</b>' + '<br><b> Total cases per 10k inhabitants </b>: %{z}<br><extra></extra>', colorscale="blues") ], 'layout': go.Layout( title="Total cases per 10000 inhabitants", mapbox_style="open-street-map", mapbox=dict( # accesstoken=token, bearing=0, center=go.layout.mapbox.Center(lat=42, lon=13), pitch=0, zoom=3.7), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)' #margin={"r":250,"t":0,"l":350,"b":150} ) }
def municipalities_limits_map(latest_local_data, municipalities_geojson_layer, variable): label = Utils.get_label_by_variable(variable) number_format = Utils.get_number_format_by_variable(variable) # print("creating figure at: " + datetime.datetime.now().strftime("%H:%M:%S")) fig = go.Figure( go.Choroplethmapbox( geojson=municipalities_geojson_layer, featureidkey="properties.CCA_2", locations=latest_local_data.code, z=latest_local_data[variable], colorscale="OrRd", # zmin=0, # zmax=12, marker_line_width=0, # text=latest_local_data.apply(lambda row: f"{row['municipality']}:<br>{row[variable]:.0f} " + label, axis=1), text=latest_local_data.apply( lambda row: "{}:<br>{} {}".format( row["municipality"], number_format.format(row[variable]), label ), axis=1 ), hoverinfo="text" ) ) fig.update_layout(mapbox_style="carto-positron", mapbox_zoom=4.5, mapbox_center = {"lat": 38.3317, "lon": -17.2836}) fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) # fig.update_layout(height=800) # print("created figure at: " + datetime.datetime.now().strftime("%H:%M:%S")) return fig
def district_map(): df1 = get_ac_re_type("district") a = dis_df.iloc[:, 1].tolist() district_list = a zeros = pd.DataFrame( 0, index=np.arange(len(district_list)), columns=["Active Cases", "Recovered Cases"], ) zeros["district"] = district_list y = ( pd.concat([df1, zeros], sort=False) .drop_duplicates(["district"]) .reset_index(drop=True) ) y = y.rename( columns={"Active Cases": "activecases", "Recovered Cases": "recoveredcases"} ) y["district"] = y["district"].str.upper() figg2 = go.Figure( go.Choroplethmapbox( featureidkey="properties.DISTRICT", geojson=nepal_districts_geo, locations=y.district, z=(y.activecases + y.recoveredcases) * 10, zauto=True, zmin=5, zmax=16, colorscale=[ "#f7fbff", "#d2e3f3", "#c6dbef", "#b3d2e9", "#85bcdb", "#6baed6", "#4292c6", "#1361a9", "#08519c", "#08306b", ], reversescale=False, marker_opacity=0.8, marker_line_width=1, customdata=np.vstack((y.district, y.activecases, y.recoveredcases)).T, hovertemplate="<b>%{customdata[0]}</b><br><br>" + "Total Cases:%{customdata[1]}<br>" + "Recovered:%{customdata[2]}<br>" + "<extra></extra>", showscale=True, ) ) figg2.update_layout( margin=dict(l=0, r=0, b=0, t=0, pad=0.8), mapbox_style="carto-positron", mapbox_zoom=5.5, mapbox_center={"lat": 28.021106723604202, "lon": 83.80321443774628}, ) return figg2
def do_countyplot(df: pd.DataFrame, thru: date): """ do_countyplot instantiates a plotly figure object with a Choropleth. fyi colorscale can be set to built in continuous such as bluered, Viridis, or ylorrd, or TODO: custom discrete colorscales can be used :param df: county-level table of covid and population data :type df: pd.DataFrame :return: fig :rtype: a plotly.graph_objects figure object """ with urlopen( 'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json' ) as response: counties = json.load(response) fig = go.Figure( go.Choroplethmapbox(geojson=counties, locations=list(df['FIPS']), z=df.DeathstoPop, customdata=df.DeathstoPop.round(2), hovertext=df.County, marker_opacity=0.5, marker_line_width=0.1, colorscale="ylorrd", colorbar_title="Fatalities per 100 people")) fig.update_layout(mapbox_style="open-street-map", mapbox_zoom=3, mapbox_center={ "lat": 37.0902, "lon": -95.7129 }) fig.update_layout(title_text='Covid-19 local mortality as of ' + thru.strftime('%m-%d-%Y') + " -python code and analysis by Brian Herbert") fig.update_layout(margin={"r": 0, "t": 32, "l": 0, "b": 0}) return fig
def do_nytcounty(df: pd.DataFrame, thru: date): """ do_nytcounty instantiates a plotly figure object with a Choropleth :param df: county-level table of covid data from New York Times :type df: pd.DataFrame :param pop: table of fips and population for all counties :type pop: pd.DataFrame :param thru: date of most recent data records :type thru: date :return: fig :rtype: a plotly.graph_objects figure object """ with urlopen( 'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json' ) as response: counties = json.load(response) fig = go.Figure( go.Choroplethmapbox(geojson=counties, locations=list(df['fips']), z=df.caserate.round(2), colorscale="Viridis", autocolorscale=True, hovertext=df.ddtodc, colorbar_title="Case Rate")) # fig.update_layout(hovermode="x unified") fig.update_layout(mapbox_style="carto-positron", mapbox_zoom=3, mapbox_center={ "lat": 37.0902, "lon": -95.7129 }) fig.update_layout(title_text='covid impact as of ' + thru.strftime('%m-%d-%Y')) return fig
def _create_map(self): ''' Generate choropleth map for given plot level''' mapdf = self.cases.summarydf.loc[(self.cases.summarydf['Area type'] == self.mapparams['plotlevel'])] f = go.Figure(go.Choroplethmapbox( geojson=self.cases.geo_data[self.mapparams['plotlevel']]["data"], locations=mapdf['Area code'], z=mapdf[self.mapparams['plotmeasure']], featureidkey="properties." + self.cases.geo_data[self.mapparams['plotlevel']]["key"], colorscale=px.colors.sequential.YlGn, text=mapdf['Area name'], customdata=mapdf, colorbar=dict(thickness=10,ypad=0,xpad=0, x=0), marker_opacity=0.5, marker_line_width=0) ) f.update_layout(mapbox_style="carto-positron",autosize=True,clickmode="event", hovermode="closest", mapbox_zoom=5, mapbox_center = {"lat": 53, "lon": -1.9},#height=468, margin={"l":20,"t":20,"r":20,"b":20}, annotations=[dict(x=0.99,y=0.99,showarrow=False,text="Weekly metrics to "+self.cases.latest_complete_week), dict(x=0.99,y=0.96,showarrow=False,text="Zoom / click on map area for detail")] ) return f
def update_usa_map(variable, date): date = dt.strptime(re.split('T| ', date)[0], '%Y-%m-%d') date = date.strftime('%#m/%#d/%Y') variable = variable df_states_tmp = df_states[df_states['date'] == date] fig = go.Figure( go.Choroplethmapbox( geojson=states, locations=df_states_tmp.fips, z=df_states_tmp[variable] + 1, colorscale="Tealgrn", showscale=False, marker_opacity=0.5, marker_line_width=0, text=df_states_tmp.state, customdata=df_states_tmp[['new_cases', 'new_deaths']], hovertemplate="<b>%{text}</b><br><br>" + "New Cases: %{customdata[0]}<br>" + "New Deaths: %{customdata[1]}<br>" + "<extra></extra>")) fig.update_layout(mapbox_style="carto-darkmatter", mapbox_zoom=3, mapbox_center={ "lat": 37.0902, "lon": -95.7129 }) fig.update_layout(clickmode='event+select') fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) return fig
def county_time_plot(data_by_date, loc, attr, data_max, data_min, title, wd=1000, ht=600): traces = [] for idx, data_locs in enumerate(data_by_date): if idx % 100 == 0: print("Adding %d"%idx) data = data_locs[attr] locs = data_locs[loc] min_val = data.min()/10.0 or 1.0 log_data = np.log10(data + min_val) log_max = np.log10(data_max + min_val) log_min = np.log10(data_min + min_val) traces.append(go.Choroplethmapbox(z=log_data, geojson=counties, locations=locs, colorscale="Viridis", zmin=log_min, zmax=log_max, marker_opacity=0.5, visible=True, text=data )) fig = go.Figure() fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) fig.add_trace(traces[-1]) fig.update_layout(mapbox_style="carto-positron", mapbox_zoom=3, mapbox_center = {"lat": 37.0902, "lon": -95.7129}, width=wd, height=ht) fig.update_layout(title_text=title) return fig
def Canada_trend_map(Trend_df, canada_trend_json): import plotly.graph_objects as go token = 'pk.eyJ1Ijoib21pZGJhZHIiLCJhIjoiY2s3eGVrM3JpMDExbDNtb3hxOWQwMWQ3bCJ9.ReYzh21GWttlycXTJ_mZJA' fig = go.Choroplethmapbox(geojson = canada_trend_json, featureidkey = "properties.region", locations = Trend_df['Locations EN'], z = Trend_df['Weekly_dif%'], zmid = 0, zmax = 50, zmin = -20, text = Trend_df['Weekly_dif%'], # hover text customdata = list(zip(Trend_df['Locations EN'], Trend_df['Last_7_days'], Trend_df['Last_14_7_days'], Trend_df['Total Cases'])), hovertemplate = '<b>Region</b>: %{customdata[0]}'+ '<br><b>Trend%</b>: %{z:,}'+ '<br><b>Avg Confirmed Cases in the last 7 days</b>: %{customdata[1]:,}'+ '<br><b>Avg Confirmed Cases in the last 14-7 days</b>: %{customdata[2]:,}'+ '<br><b>Total Confirmed Cases</b>: %{customdata[3]:,}'+ "<extra></extra>", colorscale = 'RdYlBu', autocolorscale=False, showscale = True, reversescale = True, colorbar = dict(len = 0.75, title = 'Weekly Trend', tickvals = [-20, -10, 0, 10, 20, 30, 40, 50], ticktext = ['<-20%', '-10%', '0%', '10%', '20%', '30%','40%','>50%']) , marker_line_width=0.1, marker_opacity=0.5, ) layout = go.Layout(mapbox_style="light", #title_text='2011 US Agriculture Exports by State<br>(Hover for breakdown)', mapbox_accesstoken=token, mapbox_zoom=3.2, height = 600, mapbox_center = {"lat": 52.493382, "lon": -92.962644}, hoverlabel = dict(bgcolor="white", font_size=14, font_family="Rockwell"), margin={"r":0,"t":0,"l":0,"b":0}) fig2 = go.Figure(layout=layout, data=fig) return(fig2)
def plot_chroplethmap(df): fig = go.Figure( go.Choroplethmapbox( geojson=provinces, locations=df.province, z=df.no, text=df.text, # colorscale="BuPu", colorscale=[ [0, 'rgb(16, 16, 16)'], #0 [1. / 10000, 'rgb(62, 58, 13)'], #10 [1. / 1000, 'rgb(109, 101, 10)'], #100 [1. / 100, 'rgb(156, 143, 6)'], #1000 [1. / 10, 'rgb(203, 186, 3)'], #10000 [1., 'rgb(250, 228, 0)'], #100000 ], zmin=0, zmax=max(df.no), showscale=False, marker_opacity=0.7, marker_line_width=0)) fig.update_layout(mapbox_style="carto-darkmatter", plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], mapbox_zoom=1.2, mapbox_center={ "lat": 50, "lon": 10 }) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) return fig
def figure(value, d): d = int(datetime.datetime.fromtimestamp(d).strftime("%Y%m%d")) data = df.loc[df['date'] == d][['date', 'state', value]] data['state'] = data['state'].map(states) with open('us-states.json') as json_file: geo = json.load(json_file) fig = go.Figure( go.Choroplethmapbox(geojson=geo, locations=data.state, z=data[value], colorscale="algae", marker_line_width=0.5)) fig.update_layout(mapbox_style="dark", mapbox_accesstoken=token, mapbox_zoom=3.1, mapbox_center={ "lat": 39.82, "lon": -96 }) fig.update_layout(margin={ "r": 0, "t": 0, "l": 0, "b": 0 }, paper_bgcolor='#303030', plot_bgcolor='#303030', font={'color': '#d3d3d3'}) return dcc.Graph(figure=fig)
def do_casesplot(df: pd.DataFrame, thru: date): """ do_countyplot instantiates a plotly figure object with a Choropleth :param df: county-level table of covid and population data :type df: pd.DataFrame :return: fig :rtype: a plotly.graph_objects figure object """ with urlopen( 'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json' ) as response: counties = json.load(response) fig = go.Figure( go.Choroplethmapbox(geojson=counties, locations=list(df['FIPS']), z=df.CasestoPop, colorscale="ylorrd", hovertext=df.County, marker_opacity=0.5, marker_line_width=0.2, colorbar_title="Cases per 100people")) fig.update_layout(mapbox_style="carto-positron", mapbox_zoom=3, mapbox_center={ "lat": 37.0902, "lon": -95.7129 }) fig.update_layout(title_text='Covid-19 case spread as of ' + thru.strftime('%m-%d-%Y') + " -python code and analysis by Brian Herbert") fig.update_layout(margin={"r": 0, "t": 32, "l": 0, "b": 0}) return fig
def draw_map(self, df, map_geoson, type): if type == 'Country': location_var = 'ESTU_COD_RESIDE_DEPTO_str' color_var = 'PUNT_GLOBAL' lat_center = 4.570868 lon_center = -74.2973328 zoom_val = 4 else: location_var = 'ESTU_COD_RESIDE_MCPIO_str' color_var = 'PUNT_GLOBAL' zoom_val = 6.5 lat_center, lon_center = self.get_state_center(type) fig = go.Figure( go.Choroplethmapbox( geojson=map_geoson, locations=df[location_var], z=df[color_var], colorscale="Viridis", #colorscale=["red", "green"], zmin=df[color_var].min(), zmax=df[color_var].max(), marker_opacity=0.95, marker_line_width=0.1)) fig.update_layout(mapbox_style="carto-positron", mapbox_zoom=zoom_val, mapbox_center={ "lat": lat_center, "lon": lon_center }) fig.update_layout(margin={"r": 10, "t": 10, "l": 10, "b": 10}) return fig
def display_map(tx_fips, counties): df = pd.DataFrame(tx_fips) import plotly.graph_objects as go fig = go.Figure( go.Choroplethmapbox( geojson=counties, locations=df.fips, z=df.z_value, text=df.references, colorscale="Viridis", zmin=0, zmax=6, marker_line_width=0, ) ) fig.update_layout( hovermode="closest", mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=go.layout.mapbox.Center(lat=39, lon=-64), pitch=0, zoom=2, ), ) fig.show()
def getHeatMap(df, selectedDate, intensityLevel): # Create a new colume Value df['Value'] = ( 100 - df[intensityLevel]) if intensityLevel == 'NONE' else df[intensityLevel] selected_heatmap_data = getSelectedRecord(df, selectedDate.year, selectedDate.month, selectedDate.day) fig = go.Figure( go.Choroplethmapbox(geojson=counties, locations=selected_heatmap_data['FIPS'], z=selected_heatmap_data['Value'], colorscale="OrRd", zmin=0, zmax=100, marker_opacity=0.5, marker_line_width=0.1)) fig.update_layout(mapbox_style="carto-positron", mapbox_zoom=3, mapbox_center={ "lat": 37.0902, "lon": -95.7129 }) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) return fig
def update_figure(selected): county = get_county(3610) # name = df[df['geoid'] == county['id']]['GeoName'].values[0] # county_id = df[df['geoid'] == 3610]['GEOID'] # county_index = county_id.index[0] # opacity = df[selected][county_index] * .01 # custom_df = df[df.index == county_index] # color=df[df.index == county_index] newdf = df[df['geoid'].isin([3610])] name = newdf['GeoName'].values[0] opacity = newdf['happening'].values * .01 colorsIdx = {'Democratic': 'blue', 'Republican': 'red'} colorsNum = {'Democratic': 0, 'Republican': 1} cols = newdf['party'].map(colorsIdx) p_num = newdf['party'].map(colorsNum) my_text = [ n + "<br>Happening: " + str(h) + '<br>Human-Caused: ' + str(hc) for n, h, hc in zip(list(newdf['GeoName']), list(newdf['happening']), list(newdf['human'])) ] # print(name, '\n', county_id, '\n', county_index, '\n', opacity, '\n', custom_df) fig = go.Choroplethmapbox( # colorscale = 'Blues', showscale=False, customdata=newdf, geojson=county, locations=newdf['GEOID'], z=p_num, zmin=0, zmax=1, text=my_text, autocolorscale=False, marker_opacity=opacity, marker={ 'line': { 'color': 'rgb(250,250,248)', 'width': 1, }, }, colorbar={ 'thickness': 10, 'len': 0.3, 'x': 1, 'y': 1, }) return { 'data': [fig], 'layout': go.Layout(title=name, geo_scope='usa', mapbox_style='carto-positron', mapbox_zoom=10, mapbox_center={ 'lat': 40.7302, 'lon': -73.9729 }, height=800), }
def generate_US_map(self): """ US cases by county on a tile based map :return: Choreopleth Mapbox map """ # Get County Tile Info with urllib.request.urlopen( 'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response: counties = json.load(response) # US Data by County US_county_df = pd.read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv", dtype={"fips": str}) # Choreopleth Mabox Tile Based Map US_county_map = go.Figure(go.Choroplethmapbox(geojson=counties, # based on county locations=US_county_df.fips, # use fips to graph z=US_county_df.cases, text=US_county_df.state + ", " + US_county_df.county, # hover label colorscale=["#022a52", "#153e66", "#2a4c6e", "#405e7d", "#5d7894", "#7695b5", "#a1b5c9", "#bccee0", "#d8e2ed", "#e1e7ed"], reversescale=True, # darker for more cases zmin=0, zmax=200, # color scale max marker_line_color='#c7cdd4', # county lines marker_line_width=0.02)) US_county_map.update_layout(mapbox_style="carto-positron", mapbox_zoom=3, mapbox_center={"lat": 37.0902, "lon": -95.7129}) # default zoom US_county_map.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) return US_county_map
def visualize(df, title, subtitle, center, article_id, content): import plotly.express as px mapbox_access_token = "pk.eyJ1IjoibmVvbmNvbnRyYWlscyIsImEiOiJjazhzazZxNmQwaG4xM2xtenB2YmZiaDQ5In0.CJhvMwotvbdJX4FhbyFCxA" import plotly.graph_objects as go fig = go.Figure( go.Choroplethmapbox( geojson=plotly_data, locations=df.fips, z=df.z, name="county", hoverinfo="all", text=[ f"County: {county} <br>Tokens: {x} <br>Score: {score}" for x, score, county in zip(df.tokens, df.z, df.county) ], marker_line_width=0, marker_opacity=[max(z / max(df.z), 0.1) for z in df.z], zmin=0, zmax=max(6, max(df.z)), )) fig.update_layout( mapbox_style="dark", mapbox_accesstoken=mapbox_access_token, title=title, paper_bgcolor="darkgray", plot_bgcolor="darkgray", mapbox_zoom=8, mapbox_center=center, ) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) fig.show()
def add_choro_trace(fig, montreal_data, locations, z_vals, colorscale): ''' Adds the choropleth trace, representing Montreal's neighborhoods. Note: The z values and colorscale provided ensure every neighborhood will be grey in color. Although the trace is defined using Plotly's choropleth features, we are simply defining our base map. Args: fig: The figure to add the choropleth trace to montreal_data: The data used for the trace locations: The locations (neighborhoods) to show on the trace z_vals: The table to use for the choropleth's z values colorscale: The table to use for the choropleth's color scale Returns: fig: The updated figure with the choropleth trace ''' # TODO : Draw the map base fig.add_traces( go.Choroplethmapbox( geojson=montreal_data, locations=locations, featureidkey='properties.NOM', z=z_vals, colorscale=colorscale, showscale=False, marker_line_color='white', hovertemplate=hover.map_base_hover_template(), )) return fig
def update_map(selected_date): dates = df['date'].unique() dates = dates[selected_date] filtered_df = df[df.date == dates] print(filtered_df) fig = go.Figure( go.Choroplethmapbox( geojson=counties, locations=filtered_df.fips, z=filtered_df.cases, colorscale="Inferno", zmin=0, zmax=2000, marker_opacity=0.95, marker_line_width=0, )) #colorbar={'dtick':'log_10(5)'} fig.update_layout(mapbox_style="carto-positron", mapbox_zoom=3, mapbox_center={ "lat": 37.0902, "lon": -95.7129 }) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) # print(fig) return fig
def update_figure(selected): opacity = df[selected].values * .01 fig = go.Choroplethmapbox(showscale=False, customdata=df, geojson=counties, locations=df['geoid'], z=p_num, text=df['GeoName'], autocolorscale=False, marker_opacity=opacity, marker={ 'line': { 'color': 'rgb(250,250,248)', 'width': 1, }, }, colorbar={ 'thickness': 10, 'len': 0.3, 'x': 1, 'y': 1, }) return { 'data': [fig], 'layout': go.Layout(mapbox_style='carto-positron', mapbox_zoom=3.3, mapbox_center={ 'lat': 37.0902, 'lon': -95.7129 }, height=800) }
def area_view(site): df_map_site = df_map[df_map['site'] == site] fig = go.Figure( go.Choroplethmapbox( geojson=shpData, z=df_map_site.view, # 分色資料依據 locations=df_map_site.name, # df的key colorscale='YlOrRd', marker=dict(opacity=0.8), colorbar=dict(thickness=20), )) fig.update_layout( mapbox_zoom=8.5, mapbox_center={ "lat": 25.0093, "lon": 121.6186 }, mapbox_style="open-street-map", ) fig.update_layout( margin={ "r": 0, "t": 0, "l": 0, "b": 0 }, height=600, ) return fig
def render_map(date): cur_pred_data = pred_data[pred_data["datetime"] == pd.to_datetime(date)] fig = go.Figure( go.Choroplethmapbox( geojson=geo, locations=cur_pred_data["region"], z=cur_pred_data["y"], colorscale=[[0, "rgb(184, 225, 255)"], [1, "rgb(0, 147, 255)"]], showscale=False, text="region: " + cur_pred_data["region"] + " taxi: " + cur_pred_data["y"].astype(int).astype(str), hoverinfo="text", marker_opacity=0.7, )) fig.update_layout( mapbox={ "style": "carto-positron", "center": { "lon": -73.98519, "lat": 40.74843 }, "zoom": 10, }, margin={ "r": 0, "t": 0, "l": 0, "b": 0 }, showlegend=False, ) return fig
def update_output(value): muni_stats = get_municipality_data() fig = go.Figure( go.Choroplethmapbox( geojson=GEO_DATA, locations=muni_stats["data"].admin_code, z=muni_stats["muni_averages"][value], colorscale="Viridis", marker_opacity=0.5, marker_line_width=0, customdata=muni_stats["data"].name, featureidkey="properties.admin_code", colorbar_title_text=BBR.field_to_desc(value), hovertemplate="Kommune: %{properties.name}<br />" + BBR.field_to_desc(value) + ": %{z:.1f}<extra></extra>", ) ) fig.update_layout( title="Kommunekort", mapbox_style="carto-positron", mapbox_zoom=5.8, mapbox_center={"lat": 56.1331075, "lon": 11.8389737}, margin={"l": 20, "r": 20, "t": 30, "b": 20}, ) return fig