def getFigureFor(cnt_crimes): df2 = df[df['COUNT']>cnt_crimes] fig = go.Figure(go.Densitymapbox(lat=df2['LATITUDE'], lon=df2['LONGITUDE'], z=df2['COUNT'], radius=10)) fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=-77.07, mapbox_center_lat=38.92, mapbox_zoom=11, ) fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) return fig
def update_value(value): DF = map_data[map_data.YEAR == value] fig = go.Figure( go.Densitymapbox(lat=DF['LATITUDE'], lon=DF['LONGITUDE'], radius=5)) fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=-74.013026, mapbox_center_lat=40.711085, mapbox_zoom=9) fig.update_layout(margin={"r": 1, "t": 0, "l": 0, "b": 0}) return fig
def generateFigure(offense): df_filtered = df[df['OFFENSE'] == offense.upper()] fig = go.Figure( go.Densitymapbox(lat=df_filtered['LATITUDE'], lon=df_filtered['LONGITUDE'], z=df_filtered['Count'], radius=10)) fig.update_layout( mapbox_style="stamen-terrain", mapbox_center_lon=-77.07, mapbox_center_lat=38.92, mapbox_zoom=11, ) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) return fig
def update_graph(select_years1): earthquak1 = earthquak.groupby( ['Year', 'Time', 'Date', 'Latitude', 'Longitude'])['Magnitude'].sum().reset_index() earthquak2 = earthquak1[(earthquak1['Year'] >= select_years1[0]) & (earthquak1['Year'] <= select_years1[1])] return { 'data': [ go.Densitymapbox( lon=earthquak2['Longitude'], lat=earthquak2['Latitude'], z=earthquak2['Magnitude'], radius=10, colorscale='HSV', showscale=False, # hoverinfo = 'text', # hovertext = # '<b>Year</b>: ' + earthquak2['Year'].astype(str) + '<br>' + # '<b>Time</b>: ' + earthquak2['Time'].astype(str) + '<br>' + # '<b>Date</b>: ' + earthquak2['Date'].astype(str) + '<br>' # '<b>Lat</b>: ' + [f'{x:.4f}' for x in earthquak2['Latitude']] + '<br>' + # '<b>Long</b>: ' + [f'{x:.4f}' for x in earthquak2['Longitude']] + '<br>' + # '<b>Magnitude</b>: ' + [f'{x:,.0f}' for x in earthquak2['Magnitude']] + '<br>' ) ], 'layout': go.Layout( height=550, margin={ "r": 0, "t": 0, "l": 0, "b": 0 }, hovermode='closest', mapbox=dict( accesstoken= 'pk.eyJ1IjoicXM2MjcyNTI3IiwiYSI6ImNraGRuYTF1azAxZmIycWs0cDB1NmY1ZjYifQ.I1VJ3KjeM-S613FLv3mtkw', # Create free account on Mapbox site and paste here access token center=go.layout.mapbox.Center(lat=36, lon=-5.4), # style='stamen-terrain', style='open-street-map', # style='dark', zoom=1.2), autosize=True, ) }
def update_worldmap(value): t = 60 - int(value) cases = [ COVID.all_simulated_data[x]["active"][-t] for x in COVID.all_simulated_data ] data = go.Densitymapbox(lat=COVID.lat, lon=COVID.long, z=cases, radius=30) return { 'data': [data], 'layout': go.Layout( title="Active Cases on {}".format(datetime.datetime.now().date() + datetime.timedelta(days=60 - t)), mapbox=dict(accesstoken=map_box_key, style="dark"), plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], ) }
def update_graph(industria, departamento): zoom = 4.5 lat = 7 lon = -75.566293 bearing = 0 if industria != None and departamento != None: df1 = df[(df['Actividad CIIU'] == industria) & (df['Dpto Domicilio'] == departamento)] elif industria != None: df1 = df[df['Actividad CIIU'] == industria] elif departamento != None: df1 = df[df['Dpto Domicilio'] == departamento] else: df1 = df return go.Figure( data=[ # Data for business depending on industry and department go.Densitymapbox( lat=df1.lat, lon=df1.lon, radius=10, hovertemplate='Ciudad: %{text}<extra></extra>', text=[x for x in df1['Ciudad Domicilio']], # hoverinfo= 'text', ), ], layout=Layout( autosize=True, hovermode='closest', mapbox_style="dark", margin=go.layout.Margin(l=0, r=35, t=0, b=0), showlegend=False, mapbox=dict( accesstoken=mapbox_access_token, center=dict(lat=lat, lon=lon), # 40.7272 # -73.991251 style="dark", bearing=bearing, zoom=zoom, ), ), )
def heatmap(data: 'pd.DataFrame') -> 'go.Figure': figure = go.Figure() figure.add_trace(go.Densitymapbox( lat=data['LatArea'], lon=data['LonArea'], z=data['Price'], radius=30, showscale=False, showlegend=False, zmin=100, zmax=10000 )) figure.update_layout( autosize=True, mapbox=dict(style='carto-darkmatter', zoom=5, bearing=0, pitch=30, center={"lat": data['LatArea'].median(), "lon": data['LonArea'].median()}) ) figure.update_layout( font=dict(size=15, family='Roboto', color='#333'), margin=dict(l=0, r=0, b=0, t=0, pad=0) ) return figure
def update_map(year_list, check_sev, check_car): #Filter year dff = df[df['year'].isin(year_list)] dff = apply_filter(dff, check_sev, check_car) dff = dff[['lat', 'lon', 'ID']].groupby(['lat', 'lon']).count().reset_index() # Paint mapbox into the data data = go.Data([ go.Densitymapbox(lat=dff['lat'], lon=dff['lon'], text=dff['ID'], radius=6.5, opacity=0.5, colorbar=None) ]) # Layout and mapbox properties layout = go.Layout( autosize=True, hovermode='closest', margin=go.layout.Margin(l=40, r=0, t=10, b=40), mapbox=dict(accesstoken=mapbox_access_token, bearing=0, pitch=0, zoom=11.5, style='dark'), mapbox_center={ "lat": 10.981619, "lon": -74.802569 }, paper_bgcolor=bg_color, plot_bgcolor=bg_color, ) return go.Figure(data=data, layout=layout)
def generate_heat_map_figure(year,data): # #df needs to be the totals of each district for given year print("generating") dfYear = df.loc[df["Year"] == year] # return sums = [] lats =[] longs=[] for district in dfYear.District.unique(): dfYD = dfYear.loc[df["District"] == district] district_sum = dfYD[data].sum() sums.append(district_sum) lats.append(location[district][0]) longs.append(location[district][1]) figure = go.Figure( go.Densitymapbox(lat = lats, lon = longs, z =sums, radius=100)) figure.update_layout(mapbox_center_lon = 13.381777, mapbox_center_lat = 52.531677) figure.update_layout(mapbox_style="open-street-map", uirevision = True ) figure.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) # figure.update_geos(scope = "europe" , fitbounds='locations') return figure
import pickle ########### Initiate the app external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) server = app.server app.title = 'iraq protests' ########## Define the data df = pd.read_csv('resources/iraq_protests.csv') ########## Define the figure fig = go.Figure( go.Densitymapbox(lat=df['latitude'], lon=df['longitude'], z=df['fatalities'], radius=10)) fig.update_layout( mapbox_style="stamen-terrain", mapbox_center_lon=44.4213, mapbox_center_lat=33.3248, mapbox_zoom=4, ) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) ########### Set up the layout app.layout = html.Div(children=[ html.H1('Iraq Protests'), html.Div([ dcc.Graph(id='figure-1', figure=fig),
lat=list() lng=list() for x in df['restaurant_lat_lng']: try: lat.append(float(x.split(',')[0])) except: lat.append(0.0) try: lng.append(float(x.split(',')[1])) except: lng.append(0.0) lat = pd.Series(lat).value_counts() lng = pd.Series(lng).value_counts() fig_map = go.Figure(go.Densitymapbox(lat=list(lat.index), lon=list(lng.index), z=lat.tolist(), radius=15)) fig_map.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=180, mapbox={'zoom':12, 'center':{'lat':lat.index[0], 'lon':lng.index[0]}}) fig_map.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) order_item_list=list() for x in df['order_items']: order_item_list.extend(x) order_df=pd.DataFrame.from_records(order_item_list) item_name = order_df['name'].value_counts(dropna=False).head(10) item_name = seriesToFrame(item_name, ['Item Name','Count']) is_veg = order_df['is_veg'] is_veg_list = list()
########### Initiate the app external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) server = app.server app.title = 'dc_houses_by_bedrooms' ########## Define the data df = pd.read_csv('resources/DC_Properties.csv', index_col='Unnamed: 0') df = df[df['BEDRM'].between( 0, 10)] # artificially reduce the number of data points for efficiency ########## Define the figure fig = go.Figure( go.Densitymapbox(lat=df['LATITUDE'], lon=df['LONGITUDE'], z=df['BEDRM'], radius=10)) fig.update_layout( mapbox_style="stamen-terrain", mapbox_center_lon=-77.07, mapbox_center_lat=38.92, mapbox_zoom=11, ) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) ########### Set up the layout app.layout = html.Div(children=[ html.H1('DC Houses by Number of Bedrooms'), html.Div([ dcc.Graph(id='figure-1', figure=fig),
def map(): def each_country_city_visited(country_name): list1=[str(i) for i in qp.loc[country_name]['visitedNumber']] return list1 def each_country_city_place(country_name): list1=[str(i) for i in qp.loc[country_name]['placeNumber']] return list1 def each_country_city_name(country_name): list1=[i for i in qp.loc[country_name]['city_cn']] return list1 country=request.form['country'] each_country_city_visited=each_country_city_visited(country) each_country_city_place=each_country_city_place(country) each_country_city_name=each_country_city_name(country) def bar_each_visited() -> Bar: c = ( Bar() .add_xaxis(each_country_city_name) .add_yaxis(str(country),each_country_city_visited, color=Faker.rand_color()) .set_global_opts( title_opts=opts.TitleOpts(title="Bar-"+str(country)+"各地参观(visited)数"), datazoom_opts=[opts.DataZoomOpts()], ) ) return c.render_embed() def bar_each_place() -> Bar: c = ( Bar() .add_xaxis(each_country_city_name) .add_yaxis(str(country),each_country_city_place,color=Faker.rand_color()) .set_global_opts( title_opts=opts.TitleOpts(title="Bar-"+str(country)+"各地景观/目的地数"), datazoom_opts=[opts.DataZoomOpts()], ) ) return c.render_embed() th=df.loc[country] def pie_each_country_lei() -> Pie: ss=Counter([i for i in th['catename'].fillna('未分类')]) lei=[k for k,v in ss.items()] count=[v for k,v in ss.items()] c = ( Pie() .add( "", [list(z) for z in zip(lei, count)], radius=["35%", "75%"], center=["50%", "50%"], rosetype="area", ) .set_global_opts(title_opts=opts.TitleOpts(title="Pie-"+str(country)+"景观/目的地类别示例")) ) return c.render_embed() px = th['position_x'] py = th['position_y'] pt = [i for i in th['en_destination']] pc = th['count'] x=[i for i in px] y=[i for i in py] ptc=[i for i in th['cn_destination']] ptt=[str(ptc[i])+str(pt[i]) for i in range(len(ptc))] fig = go.Figure(go.Densitymapbox( name=str(country)+'热力图', lat=px, lon=py, z=pc, radius=25, text=ptt)) fig.update_layout( title=str(country)+'热力图', paper_bgcolor='rgba(170,95,134,1)', plot_bgcolor='rgba(170,95,134,1)', mapbox=dict( style='outdoors', accesstoken=mapbox_access_token, bearing=0, center=dict( lat=float(x[0]), lon=float(y[0]), ), pitch=0, zoom=4 ), ) data = [ go.Scattermapbox( name=str(country)+'散点图', lat=px, lon=py, mode='markers', marker=dict( size=9 ), text=ptt, )] layout1 = go.Layout( title=str(country)+'散点图', autosize=True, hovermode='closest', paper_bgcolor='rgba(170,95,134,1)', plot_bgcolor='rgba(170,95,134,1)', mapbox=dict( style='outdoors', accesstoken=mapbox_access_token, bearing=0, center=dict( lat=float(x[0]), lon=float(y[0]) ), pitch=0, zoom=4 ), ) fig1 = dict(data=data, layout=layout1) div1=plot(fig,output_type="div") div2=plot(fig1,output_type="div") html1=bar_each_visited() html2=bar_each_place() html3=pie_each_country_lei() each_sea_text=minding.each_sea[country] html='''{% extends 'base.html' %} {% block body %} '''+''' <div class='daxiao'> {div1} </div> <div class='daxiao'> {div2} </div> <div class='each_country'> {html1} </div> <div class='each_country'> {html2} </div> <div class='each_country'> {html3} </div> <div class='font'> {each_sea_text} </div> '''.format(div1=div1,div2=div2,html1=html1,html2=html2,html3=html3,each_sea_text=each_sea_text)+''' {% endblock %} ''' with open(dir_path+'/templates/'+str(country)+'.html','w',encoding='utf-8') as f: f.write(html) return render_template(str(country)+'.html')
"height": "600px" }), dcc.Graph( id="india-map", style={ 'width': '50%', 'display': 'inline-block', 'textAlign': 'right', "height": "600px" }, figure={ 'data': [ go.Densitymapbox( lat=COVID.indian_lat, lon=COVID.indian_long, z=[ COVID.indian_data[x]["active"][-1] for x in COVID.indian_data ], radius=50) ], 'layout': go.Layout( title="Active Cases on {}".format( datetime.datetime.now().date()), mapbox=dict(accesstoken=map_box_key, style="dark", center=dict(lat=20.5937, lon=78.9629), zoom=4), plot_bgcolor=colors['background'], paper_bgcolor=colors['background'],
import pickle ########### Initiate the app external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) server = app.server app.title = 'dc crime' ########## Define the data df = pd.read_csv('resources/crime_shortdf.csv') ########## Define the figure fig = go.Figure( go.Densitymapbox(lat=df['LATITUDE'], lon=df['LONGITUDE'], z=df['COUNT'], radius=15)) fig.update_layout( mapbox_style="stamen-terrain", mapbox_center_lon=-77.07, mapbox_center_lat=38.92, mapbox_zoom=11, ) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) ########### Set up the layout app.layout = html.Div(children=[ html.H1('Number of Crimes by Area'), html.Div([ dcc.Graph(id='figure-1', figure=fig),
import firebase_admin from firebase_admin import credentials from firebase_admin import firestore import json import plotly.graph_objs as go import pandas as pd cred = credentials.Certificate("credentials.json") firebase_admin.initialize_app(cred) db = firestore.client() doc_ref = db.collection(u'dashboard').document( u'cik8wqMjh7RZMgtmSGxj').collection(u'list').document( u'R9L8hUElfZ55FH4OG0TP') doc = doc_ref.get().to_dict() data = json.loads(doc["data"]["heatmap"]) center = json.loads(doc["data"]["center"]) df = pd.DataFrame.from_dict(data, orient="columns") heatmap_fig = go.Figure( go.Densitymapbox(lat=df["lat"], lon=df["lng"], z=df["val"], radius=8)) heatmap_fig.update_layout(mapbox_style="open-street-map", mapbox_center_lon=center["lng"], mapbox_center_lat=center["lat"], mapbox_zoom=17) heatmap_fig.update_layout(margin={"r": 0, "t": 60, "l": 20, "b": 0})
def init_data(server): dash_app = Dash( server=server, routes_pathname_prefix='/dash/data/', ) colors = { 'background': '#FFFFFF', 'text': '#111111' } dash_app.layout = html.Div(style={'backgroundColor': colors['background']}, children=[ html.H1( children='Berlin Crimes', style={ 'textAlign': 'center', 'color': colors['text'] } ), dcc.Graph( id='Data', figure={ 'data': [ go.Densitymapbox() for i in df.District.unique() ], # 'layout': { # 'plot_bgcolor': colors['background'], # 'paper_bgcolor': colors['background'], # 'font': { # 'color': colors['text'] # } # } } ), html.H2(id = "axis", children="X-Axis"), dcc.Dropdown( id="x-axis", options=[ ({"label": i, "value": i}) for i in df.columns ], value=df.columns[6] ), html.H2(children="Y-Axis"), dcc.Dropdown( id="y-axis", options=[ ({"label": i, "value": i}) for i in df.columns], value=df.columns[6] ), dcc.Graph( id='MapBox', figure=generate_heat_map_figure(2012,"Sum") ), html.H2(id="data_title", children="Geo Data"), dcc.Dropdown( id="geo-data", options=[ ({"label": i, "value": i}) for i in df.columns ], value=df.columns[6] ), html.H2(children="Year"), dcc.Dropdown( id="year", options=[ ({"label": i, "value": i}) for i in df["Year"].unique()], value="2012" ), ]) init_callbacks(dash_app) return dash_app.server
def update_figure(fish_value, param_value, depth_value, year_value): # print(fish_value, param_value, depth_value, year_value) if fish_value == 'total': locations = fish_locations[fish_locations['year'] == year_value].copy() else: locations = fish_locations[ (fish_locations['fish_type'] == fish_value) & (fish_locations['year'] == year_value)].copy() color_value = param_data[(param_data.depth_range == depth_value) & ( param_data.year == year_value)][param_value].item() map_color, map_colorscale = get_color(color_value, param_value) return { 'data': [ go.Densitymapbox(lat=locations['latitude'].tolist(), lon=locations['longitude'].tolist(), radius=10, showscale=False, hoverinfo='skip'), # Creating hidden heatmap so that colorscale for parameter average can show on the right side of the plot go.Heatmap(z=[ list(param_data[param_value]), ], colorscale=[[0.0, "rgb(96,118,142)"], [0.1, "rgb(106,129,150)"], [0.2, "rgb(115,140,159)"], [0.3, "rgb(125,151,167)"], [0.4, "rgb(134,162,175)"], [0.5, "rgb(144,173,184)"], [0.6, "rgb(153,183,192)"], [0.7, "rgb(163,194,200)"], [0.8, "rgb(172,205,208)"], [0.9, "rgb(182,216,217)"], [1.0, "rgb(191,227,225)"]], colorbar=dict( title=f"{param_value}", titleside="top", tickmode="array", tickvals=map_colorscale, )) ], 'layout': go.Layout(autosize=True, hovermode='closest', height=600, margin=dict(l=0, r=0, b=0, t=0, pad=0), mapbox={ 'accesstoken': cfg.MAPBOX_TOKEN, 'bearing': 0, 'layers': [ dict(sourcetype='geojson', source=gulf_geojson, type='fill', color=map_color) ], 'center': { 'lat': 48.3, 'lon': -64.5 }, 'zoom': 5, 'style': 'mapbox://styles/mapbox/light-v9' }) }
html.Div(children=""" DRP: A interactive data analytics platform for Disaster Risk Topics """), dcc.Graph(id="earthquake-scattermap", figure=px.scatter_mapbox( df_eqs, lat="lati", lon="long", color="mag", size="mag", animation_frame="year", title="Earthquake location and magnitude by year")), dcc.Graph(id="earthquake-densitymap", figure=go.Figure( data=go.Densitymapbox(lat=df_eqs.lati, lon=df_eqs.long, z=df_eqs.mag, radius=10), layout=go.Layout( title=go.layout.Title(text="Earthquake density map"), mapbox_style="stamen-terrain"))), dcc.Graph(id="tsunami-map", figure=go.Figure( data=go.Choroplethmapbox(geojson=tsunamis, locations=df_tsu.id, z=df_tsu.shape_area), layout=go.Layout(title=go.layout.Title( text="Tsunamis inundation risk in Lima"), mapbox_style="carto-positron"))) ], style={'columnCount': 2})
import numpy as np import chart_studio as cs import plotly.graph_objs as go """ Process Model data (which is output into 'export1.csv') and graph it into a heatmap. """ inp = pd.read_csv("export1.csv") print(inp) cs.tools.set_credentials_file(username='******', api_key='plotly api key') cs.tools.set_config_file(world_readable=True, sharing='public') fig = go.Figure( go.Densitymapbox(lat=inp.Latitude, lon=inp.Longitude, z=inp.Flood, radius=20)) fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=-95.7, mapbox_center_lat=30.62, mapbox_zoom=7.5) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) fig.show() layout = go.Layout(title='Flood Heatmap (Higher Value = safer)') fig = go.Figure(data=fig, layout=layout) cs.plotly.plot(fig, filename='Flood Heat Map (Higher Value = Safer)')
hovermode='closest', margin = {'l': 0, 'r': 0, 'b': 0, 't': 0}, mapbox=dict( accesstoken='pk.eyJ1IjoibGVvbmFyZG9iZXRhbmN1ciIsImEiOiJjazlybGNiZWcwYjZ6M2dwNGY4MmY2eGpwIn0.EJjpR4klZpOHSfdm7Tsfkw', bearing=0, center=go.layout.mapbox.Center( lat= 6.240737, lon= -75.589900 ), pitch=0, zoom=9.5 ) ) """ fig = go.Figure( go.Densitymapbox(lat=latitudes, lon=longitudes, z=valorpm[0], radius=10)) fig.update_layout(mapbox_style="satellite-streets", mapbox_center_lon=-75.589900) fig.update_layout( margin={ "r": 0, "t": 0, "l": 0, "b": 0 }, mapbox=dict( accesstoken= 'pk.eyJ1IjoibGVvbmFyZG9iZXRhbmN1ciIsImEiOiJjazlybGNiZWcwYjZ6M2dwNGY4MmY2eGpwIn0.EJjpR4klZpOHSfdm7Tsfkw', bearing=0, center=go.layout.mapbox.Center(lat=6.240737, lon=-75.589900), zoom=9.5))
def actualizar_figura(datepicker,hora): fecha_elegida=str(datetime.strptime(datepicker.split('T')[0],'%Y-%m-%d')+timedelta(hours=hora)) band=True muestra=0 for lec in range(len(fechas)): if (fechas[lec]==fecha_elegida): band=False muestra=lec if band: band = True muestra=0 if (not band): """ grid_z0 = griddata(puntos, valorpm[muestra], (grid_x, grid_y), method='nearest') grid_z2 = griddata(puntos, valorpm[muestra], (grid_x, grid_y), method='cubic') for k in range (len(grid_z2)): for p in range (len(grid_z2[k])): if np.isnan(grid_z2[k][p]): grid_z2[k][p]=grid_z0[k][p] valorgrid2=[] for zg in grid_z2: for zp in zg: valorgrid2.append(zp) """ figure = go.Figure(go.Densitymapbox(lat=latnew, lon=lonnew, z=zinterpolacion[muestra],radius=15)) figure.update_layout(mapbox_style="satellite-streets", mapbox_center_lon=-75.589900,mapbox_center_lat= 6.240737) figure.update_layout( margin={"r":0,"t":0,"l":0,"b":0}, mapbox=dict( accesstoken='pk.eyJ1IjoibGVvbmFyZG9iZXRhbmN1ciIsImEiOiJjazlybGNiZWcwYjZ6M2dwNGY4MmY2eGpwIn0.EJjpR4klZpOHSfdm7Tsfkw', bearing=0, center=go.layout.mapbox.Center( lat= 6.240737, lon= -75.589900 ), zoom=9.5 ) ) figure.show() else: figure={ 'data': [{ 'lat': latitudes, 'lon': longitudes, 'text': nombres, 'marker': { 'color': '#00ff00', 'size': 10, 'opacity': 0.6 }, 'style': "stamen-terrain", 'type': 'scattermapbox' }], 'layout': { 'mapbox': { 'accesstoken': 'pk.eyJ1IjoibGVvbmFyZG9iZXRhbmN1ciIsImEiOiJjazlybGNiZWcwYjZ6M2dwNGY4MmY2eGpwIn0.EJjpR4klZpOHSfdm7Tsfkw', 'style': "satellite-streets", 'center' : { 'lat': 6.240737, 'lon': -75.589900 }, 'zoom' : 9.5 }, 'hovermode': 'closest', 'margin': {'l': 0, 'r': 0, 'b': 0, 't': 0} }} return figure
------ '''), html.Div([dcc.Graph( id='heat_map', figure={ 'data':[go.Scattermapbox( lat=pizza_data.latitude, lon=pizza_data.longitude, mode='markers', marker=go.scattermapbox.Marker(size=9,opacity=0.0000001), text="Restaurant Name: " + pizza_data['name'] + "<br>City: " + pizza_data['city'], ), go.Densitymapbox(lat=pizza_data.latitude, lon=pizza_data.longitude, hoverinfo="skip", radius=radius)], 'layout':go.Layout( title=go.layout.Title(text='Dash Data Visualization'), autosize=True, mapbox_style= 'stamen-terrain', mapbox_center_lon=np.mean(pizza_data.longitude), mapbox_center_lat=np.mean(pizza_data.latitude), margin={"r":0,"t":0,"l":0,"b":0}) } ) ],style={'width': '100%', 'display': 'inline-block', 'padding': '0 20'}), dcc.Markdown(''' **Darker the region indicates higher demand**
def generate_map(): nypd_commands = pd.read_pickle('data/command_locations_df.pkl') count_by_commands = data.groupby( 'Command')['Unique Id'].count().reset_index() count_by_commands['Command'] = count_by_commands['Command'].apply( lambda x: ''.join(x.split(' ')).lower()) count_by_commands['Command'] = count_by_commands['Command'].apply( lambda x: utils.get_command(x, COMMAND_KEY)) count_by_commands = count_by_commands.dropna() count_by_commands = count_by_commands.rename( columns={'Unique Id': 'count'}) count_by_commands = count_by_commands.set_index('Command').join( nypd_commands[['commands', 'lat', 'lng']].set_index('commands')) total = len(data) sustained_pct = outcomes[outcomes['Disposition'] == 'Sustained']['count'].iloc[0] / len(data) * 100 fig = go.Figure( go.Densitymapbox(lat=count_by_commands['lat'], lon=count_by_commands['lng'], colorscale='viridis', z=count_by_commands['count'], radius=20, showscale=False, hovertemplate='%{text}: %{z}<extra></extra>', text=count_by_commands.index)) fig.update_layout( mapbox_style="carto-positron", mapbox_center_lon=-73.77, mapbox_center_lat=40.75, mapbox_zoom=10.6, height=450, margin=dict(l=3, r=3, b=3, t=0), annotations=[ dict(x=0.9, y=0.661, showarrow=False, bordercolor='black', text="NYPD 1986 - 2020", bgcolor="white", font=dict(family="Times New Roman, Helvetica", size=25), xref="paper", yref="paper", width=350, height=40), dict(x=0.9, y=0.5775, showarrow=False, text="{:,d} allegations".format(total), bordercolor='black', bgcolor="white", font=dict(family="Impact, Times New Roman, Helvetica", size=30), xref="paper", yref="paper", width=350, height=40), dict(x=0.9, y=0.489, showarrow=False, text="{:.1f}% disciplined".format(sustained_pct), bgcolor="white", bordercolor='black', font=dict(family="Impact, Times New Roman, Helvetica", size=30, color="red"), xref="paper", yref="paper", width=350, height=40) ]) config = dict({'scrollZoom': False}) fig.write_html(file='templates/map.html', config=config, include_plotlyjs='cdn')
center=center, zoom=13) fig.add_scattergeo(lat=tubes.Latitude, lon=tubes.Longitude) fig.show() # from plotly.offline import init_notebook_mode, iplot import plotly.graph_objs as go # init_notebook_mode() mapbox_access_token = '...' data = [ go.Densitymapbox(lat=df.Latitude, lon=df.Longitude, radius=9, colorscale='Blackbody'), go.Densitymapbox(lat=tubes.Latitude, lon=tubes.Longitude, radius=9) ] layout = go.Layout( autosize=True, hovermode='closest', mapbox=dict(style='open-street-map', center=center, zoom=13), ) fig = go.Figure(data=data, layout=layout) fig.show() def example_multi():