def plot_points_on_map(cl_list): # Old API token, don't waste your time ;) mapbox_access_token = "pk.eyJ1IjoiYXBvc3RvbGVzY3VzIiwiYSI6ImNrNjg5MXd0dDAyZ3gzbWxhaTNwOGR1b2oifQ.O-vXy2D0ZN7LUhg0IwIKTQ" x_array = [] y_array = [] z_array = [] counter = 0 for i in cl_list: x_array.append(i.center_lat) y_array.append(i.center_lon) z_array.append(i.points) fig = go.Figure( go.Densitymapbox(lat=x_array, lon=y_array, z=z_array, radius=z_array)) fig.update_layout(mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=go.layout.mapbox.Center(lat=44.4268, lon=26.1025), zoom=12, )) # fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) fig.show()
def update_graph_analyse_heatmap(value): df = get_dataset_users() scale = 1e7 if value == 1: temp = df['aweme_count'] statement = '视频数' elif value == 2: temp = df['total_favorited'] / scale statement = '千万点赞量' else: temp = df['mplatform_followers_count'] / scale statement = '千万粉丝量' df['text'] = df['city'] + '<br>' + (temp).astype(str) fig = go.Figure( go.Densitymapbox(lon=df['lon'], lat=df['lat'], hovertemplate=df['text'], z=temp, colorbar_title=statement, name=statement # colorscale=[[0, "#ff0000"], [1, "#ffff00"]], )) fig.update_layout( # title_text='用户视频点赞/粉丝 热力图', # showlegend=True, # height=600, width=750, mapbox=dict(zoom=3, center={ 'lat': 36.3043, 'lon': 103.5901 })) fig.update_layout(mapbox_style="light", mapbox_accesstoken=MAPBOX_TOKEN) fig.update_layout(margin={"r": 0, "t": 20, "l": 0, "b": 0}) return fig
def update_map(n, time_value): streetlight_df['time_norm'] = time_value / 24 streetlight_df['cos_time'] = streetlight_df['time_norm'].apply( lambda x: (math.cos(x * 2 * math.pi) * -2)) streetlight_df['time_intensity'] = streetlight_df[ 'distance_centre_norm'] * streetlight_df['cos_time'] streetlight_df['time_intensity_norm'] = ( streetlight_df['time_intensity'] - min(streetlight_df['time_intensity'])) / ( max(streetlight_df['time_intensity']) - min(streetlight_df['time_intensity'])) fig = go.Figure( go.Densitymapbox(lat=streetlight_df['lat'], lon=streetlight_df['lng'], z=streetlight_df['time_intensity_norm'], radius=1)) fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=streetlight_df['lng'][0], mapbox_center_lat=streetlight_df['lat'][0], mapbox_zoom=11) fig.update_layout(showlegend=False) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) return fig
def show_plotly(request): data_f = pd.read_csv(root_for_files + 'ready_build_graph.csv') df_temp = data_f.groupby(['Location']).sum().reset_index(drop=False) fig = px.scatter(df_temp, x=df_temp['RainToday'], y=df_temp['Location'], size=df_temp['Rainfall'], color=df_temp['RainToday'], height=800) lat = data_f.groupby('Location').mean().Latitude lon = data_f.groupby('Location').mean().Longitude z = data_f.groupby('Location').mean()['Rainfall'] fig_2 = go.Figure(go.Densitymapbox(lat=lat, lon=lon, z=z, radius=30)) fig_2.update_layout(mapbox_style="open-street-map", mapbox_center_lon=133.7751312, mapbox_center_lat=-25.2743988) fig_2 = plot(fig_2, output_type='div', include_plotlyjs=False, show_link=False, link_text="") fig = plot(fig, output_type='div', include_plotlyjs=False, show_link=False, link_text="") return render(request, "graph.html", context={'fig': fig, 'fig_2': fig_2})
def plot_map(data): """Plotting new map Arguments: data {df} -- [dataframe containing at leat 3 columns: lat, lng, val] Returns: json -- JSON file with info about plotly figure """ fig = go.Figure( go.Densitymapbox(lat=data.lat, lon=data.lng, z=data.val, radius=15, opacity=0.7)) fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=19.947015, mapbox_center_lat=50.055163, mapbox_zoom=9) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) fig.layout.template = None graphJSON = json.dumps(fig, cls=plotly.utils.PlotlyJSONEncoder) return graphJSON
def plot_hole_distribution( self, ax, hole, stroke, score, t_round=None, flag_loc=None, N=100, plotly=True, ): par = list(self.__course_par.values())[0].get(hole) color_map = self.color_palette(score, par) X, Y, f = self.hole_distribution(hole, stroke, score, t_round, flag_loc, N, plotly) if f is not None: if plotly: ax.add_trace( go.Densitymapbox( lat=X.ravel(), lon=Y.ravel(), z=f.ravel(), colorscale=color_map["plotly"], radius=20, showlegend=False, showscale=False, hoverinfo="skip", )) else: ax.contour(X, Y, f, alpha=0.5, cmap=color_map["cmap"]) return ax
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 generate_map(results): fig = go.Figure( go.Densitymapbox(lat=results.latitude, lon=results.longitude, z=results.Risk, radius=1)) fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=180) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) return fig.show()
def map_colegios(df): tmp = df[['COLE_NOMBRE','LATITUD','LONGITUD']].copy() tmp['z'] = 1 fig = go.Figure(go.Densitymapbox(lat=tmp['LATITUD'], lon=tmp['LONGITUD'], z=tmp['z'], radius=10)) fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=-74.2973328, mapbox_center_lat=4.570868, mapbox_zoom=4 ) fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) return fig
def data_mapaverage(): df = data_zomato() fig = go.Figure( go.Densitymapbox(lat=df.Latitude, lon=df.Longitude, z=df['Average Cost for two ($USD)'], radius=10)) fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=180) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) fig_json = json.dumps( fig, cls=plotly.utils.PlotlyJSONEncoder) # converting plotly to json file return fig_json
def add_heatmap_demo(self, **kwargs): """Adds a heatmap to the map.""" quakes = pd.read_csv( "https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv" ) heatmap = go.Densitymapbox( lat=quakes.Latitude, lon=quakes.Longitude, z=quakes.Magnitude, radius=10, name="Earthquake", **kwargs, ) self.add_basemap("Stamen.Terrain") self.add_trace(heatmap)
def make_mapa_plot(label_copy, est): mapa = go.Figure() mapa.add_trace(go.Scattermapbox( lat=est['lat'], lon=est['lng'], mode='markers', marker=go.scattermapbox.Marker( size=14, color='#404042', symbol='marker' ), text=est['Estacao'], )) mapa.add_trace(go.Densitymapbox( lat=label_copy['lat'], lon=label_copy['lng'], z=[1] * label_copy.shape[0], radius=5, colorscale='Tealgrn', reversescale=False, opacity=0.75, showscale=False )) mapa.update_layout( hovermode='closest', mapbox=dict( accesstoken=token, bearing=0, center=go.layout.mapbox.Center( lat=-23.6634526, lon=-46.5248255 ), style='light', pitch=0, zoom=11.5 ), width=500, height=550, showlegend=False, margin=dict(l=0, r=0, t=0, b=0), **plot_layout_kwargs ) return mapa
def create_image_overlay(withFault=False, anomaly_type='isostatic'): mapbox_layers_list = [county_border_layer] marker_color = stations.isostatic_anom colorbar_title = "Isostatic<br>Anomaly" if anomaly_type == 'isostatic': mapbox_layers_list.append(ca_raster_layer) mapbox_layers_list.append(nv_raster_layer) elif anomaly_type == 'bouguer': marker_color = stations.Bouguer_anom_267 colorbar_title = "Bouguer<br>Anomaly" mapbox_layers_list.append(ca_bouguer_raster_layer) mapbox_layers_list.append(nv_bouguer_raster_layer) elif anomaly_type == 'freeair': marker_color = stations.Free_air_anom colorbar_title = "Free Air<br>Anomaly" mapbox_layers_list.append(ca_freeair_raster_layer) mapbox_layers_list.append(nv_freeair_raster_layer) elif anomaly_type == 'observed': marker_color = stations.obs_grav colorbar_title = "Observed<br>Anomaly" mapbox_layers_list.append(ca_observed_raster_layer) mapbox_layers_list.append(nv_observed_raster_layer) fig = go.Figure( go.Densitymapbox( lat=stations[:1].latitude, lon=stations[:1].longitude, z=marker_color, colorscale='spectral_r', colorbar=dict( title=dict(text=colorbar_title + "<br>(mGal)", side="bottom"), outlinewidth=0, ), opacity=0, hoverinfo='skip', )) if (withFault): mapbox_layers_list.append(qfault_normal_layer) mapbox_layers_list.append(qfault_strikeslip_layer) mapbox_layers_list.append(qfault_thrust_layer) mapbox_layers_list.append(qfault_unassigned_layer) add_fault_trace(fig) fig.update_layout(mapbox_layers=mapbox_layers_list) else: fig.update_layout(mapbox_layers=mapbox_layers_list) return fig
def add_heatmap( self, data, latitude="latitude", longitude="longitude", z="value", radius=10, colorscale=None, name="Heat map", **kwargs, ): """Adds a heat map to the map. Reference: https://plotly.com/python/mapbox-density-heatmaps Args: data (str | pd.DataFrame): File path or HTTP URL to the input file or a . For example, https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv latitude (str, optional): The column name of latitude. Defaults to "latitude". longitude (str, optional): The column name of longitude. Defaults to "longitude". z (str, optional): The column name of z values. Defaults to "value". radius (int, optional): Radius of each “point” of the heatmap. Defaults to 25. colorscale (str, optional): Color scale of the data, e.g., Viridis. See https://plotly.com/python/builtin-colorscales. Defaults to None. name (str, optional): Layer name to use. Defaults to "Heat map". """ if isinstance(data, str): df = pd.read_csv(data) elif isinstance(data, pd.DataFrame): df = data else: raise ValueError("data must be a DataFrame or a file path.") heatmap = go.Densitymapbox( lat=df[latitude], lon=df[longitude], z=df[z], radius=radius, colorscale=colorscale, name=name, **kwargs, ) self.add_trace(heatmap)
def update_geo(n_clicks, start_date, end_date, countries): if "All" in countries: data = df.loc[ start_date:end_date ][["id_tweet", "latitude", "longitude"] ].drop_duplicates( subset=["id_tweet"] ) else: data = df[ (df["country"].isin(countries)) ].loc[ start_date:end_date ][["id_tweet", "latitude", "longitude"] ].drop_duplicates( subset=["id_tweet"] ) traces = [ go.Densitymapbox( lat=data["latitude"], lon=data["longitude"], z=df.loc[start_date:end_date]["id_tweet"], radius=15, colorscale="Blues", showscale=False, opacity=0.65 ) ] layout = go.Layout( title="Tweets by Location", hovermode="closest", mapbox_style="stamen-toner", mapbox_center_lon=-15, mapbox_center_lat=35 ) fig_dict = {"data": traces, "layout": layout} return fig_dict
def update_map(year, classification): #Update dataframe with the passed value dff = df[(df['year'] >= year[0]) & (df['year'] <= year[1])] dff_c = dff[dff['classification'] == 'empty'] for classes in classification: dff_c = dff_c.append(dff[dff['classification'] == classes], ignore_index=True) # Paint mapbox into the data mapdata = go.Data([ go.Densitymapbox(lat=dff_c['latitude'], lon=dff_c['longitude'], text=dff_c['number'], customdata=dff_c['number'], colorscale='hot', visible=True, colorbar=dict( borderwidth=1, xpad=1, ypad=1, thickness=3)) ], ) # Layout and mapbox properties layout = go.Layout( #autosize=True, hovermode='closest', mapbox=dict( accesstoken=mapbox_access_token, bearing=0, pitch=0, center=dict(lat=34.5, lon=-94.8), zoom=4, style='mapbox://styles/caldashvinng/ck5i8qzci0t8t1iphlvn9sdz7'), margin={ 'l': 0, 'b': 0, 't': 0, 'r': 0 }, ) return go.Figure(data=mapdata, layout=layout)
def update_accident_chart(type_accident, day_accident, start_date, end_date, value): dff = filter_df_coord(type_accident, day_accident, start_date, end_date, value) z1 = dff[['latitud', 'longitud', 'HOUR']].groupby(['latitud', 'longitud']).count().reset_index() z2 = dff[['latitud', 'longitud']].groupby(['latitud', 'longitud']).count().reset_index() ht_mat = go.Densitymapbox( lat=z2['latitud'], lon=z2['longitud'], z=z1['HOUR'], name='Inj, Dam, Dea', colorscale=heatmapstyle, autocolorscale=False, reversescale=reversecolorscale, ) # pdb.set_trace() return { 'data': [ht_mat], 'layout': go.Layout(mapbox_style="stamen-terrain", mapbox_accesstoken=token, mapbox_zoom=12, margin={ 't': 0, 'l': 0, 'r': 0, 'b': 30 }, mapbox_center={ "lat": 6.246260, "lon": -75.575259 }) }
def __init__(self, data: DataFrame, radius: int = 10, style: MapboxStyle = MapboxStyle.STAMEN_TERRAIN, access_token: str = None): assert self.LAT in data.columns, 'Data has to contain column {}'.format( self.LAT) assert self.LON in data.columns, 'Data has to contain column {}'.format( self.LON) if style == MapboxStyle.DARK: assert access_token is not None, 'Access token has to be ' + \ 'provided for dark mapbox tiles' self.data = data self.fig = go.Figure( go.Densitymapbox(lat=data[self.LAT], lon=data[self.LON], radius=radius)) self.style = style self.access_token = access_token
def _build_combined_map(self, show_trees: bool = False, heatmap_radius: float = HEATMAP_RADIUS) -> html.Div: if show_trees is True: layers = [{ 'sourcetype': 'geojson', 'source': self.trees_geojson, 'type': 'circle', 'color': TREE_COLOR, 'circle': { 'radius': TREE_RADIUS }, }] else: layers = [] fig = go.Figure( go.Densitymapbox( lat=self.bus_df_co2.latbin, lon=self.bus_df_co2.lonbin, z=self.bus_df_co2.co2_per_year_with_trees, radius=max(1, heatmap_radius) ) ) fig.update_layout( mapbox={ 'style': 'carto-positron', 'zoom': 12, 'center': { 'lon': 17.1077, 'lat': 48.1486 }, 'layers': layers } ) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) return html.Div( children=[ dcc.Graph(figure=fig, style={"height": "75vh"}) ], id='map-output' )
def create_density_heatmap(withFault=False): fig = go.Figure( go.Densitymapbox( lat=stations.latitude, lon=stations.longitude, z=stations.isostatic_anom, radius=10, # default: 30 colorscale='spectral_r', colorbar=dict( title=dict(text="Density of<br>Stations", side="bottom"), outlinewidth=0, tickmode='array', ticktext=['low', 'high'], tickvals=[1, 99], ), customdata=list( zip(stations.isostatic_anom, stations.station_id, stations.sea_level_elev_ft, stations.Free_air_anom, stations.Bouguer_anom_267, stations.obs_grav)), hovertemplate="Station ID: %{customdata[1]}<br>" "Latitude: %{lat}°<br>" "Longitude: %{lon}°<br>" "Isostatic Anomaly: %{customdata[0]} mGal<br>" "Free Air Anomaly: %{customdata[3]} mGal<br>" "Bouguer Anomaly: %{customdata[4]} mGal<br>" "Observed Gravity Anomaly: %{customdata[5]} mGal<br>" "Elevation: %{customdata[2]} ft<extra></extra>", name="Stations", )) if (withFault): add_fault_trace(fig) fig.update_layout(mapbox_layers=[ county_border_layer, qfault_normal_layer, qfault_strikeslip_layer, qfault_thrust_layer, qfault_unassigned_layer ]) else: fig.update_layout(mapbox_layers=[county_border_layer]) return fig
def same_job_diff_loc(self): for job in self.job_list: job = ''.join(job.split(" ")).replace('/', '') df = pd.read_csv( 'C:/Desktop/BigData_proj/job_analysis/salary_csv/job/{}_salary.csv' .format(job)) mymap = go.Densitymapbox(lat=df.lat, lon=df.lon, z=df.salary_med) fig = go.Figure(mymap) token = 'pk.eyJ1IjoiY3N5MTAzMCIsImEiOiJja2NjaXlnZjYwNTJ1Mnluemx1dzlzZnd2In0.5u5tGKbh0fNfzkiij9z6hg' fig.update_layout(mapbox={ 'accesstoken': token, 'center': { 'lon': -97.41107, 'lat': 42.03271 }, 'zoom': 3.2 }, margin={ 'l': 0, 'r': 0, 't': 0, 'b': 0 }) fig.show()
decent = px.density_mapbox(coords, lat='lat', lon='long', z='freq', radius=20, center={ "lat": 24, "lon": 78 }, zoom=5, mapbox_style="stamen-terrain") decent.update_layout(title="Geographical mentions") epic = go.Figure( go.Densitymapbox(lat=coords['lat'], lon=coords['long'], z=coords['freq'], radius=20)) epic.update_layout(mapbox_style="carto-darkmatter", mapbox_center_lon=78, mapbox_center_lat=24, mapbox_zoom=2.8) epic.update_layout(margin={"r": 100, "t": 0, "l": 50, "b": 20}) barg = px.bar() main.update_layout(plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], font_color=colors['text']) dark.update_layout(plot_bgcolor=colors['background'], paper_bgcolor=colors['background'], font_color=colors['text'])
def geo_located_heatmap(sum): fig_dict = dict(data=go.Densitymapbox( lat=summed_array[0][0] if sum else inst_array[0][0], lon=summed_array[0][1] if sum else inst_array[0][1], z=np.log10(summed_array[0][2]) if sum else inst_array[0][2], customdata=summed_array[0][2], hovertemplate='%{customdata}' if sum else None, radius=plot_radius, hoverinfo='z' if not sum else None, coloraxis="coloraxis"), layout={}, frames=[go.Frame(data=go.Densitymapbox( lat=summed_array[i][0] if sum else inst_array[i][0], lon=summed_array[i][1] if sum else inst_array[i][1], z=np.log10(summed_array[i][2]) if sum else inst_array[i][2], customdata=summed_array[i][2], hovertemplate='%{customdata}' if sum else None, radius=plot_radius, hoverinfo='z' if not sum else None, showscale=False, ), name=step_time_values[i], ) for i in step_num] ) fig_dict['layout'] = dict( # title={"text": "Fuel Consumption", "font": colorbar_font, 'yanchor': 'middle', 'xanchor': 'center'} if sum # else {"text": "Instantaneous Fuel Consumption", "font": colorbar_font, 'yanchor': 'middle', 'xanchor': 'center'}, font=colorbar_font, paper_bgcolor='rgb(249, 249, 249)', hovermode='closest', margin=go.layout.Margin( l=20, # left margin r=0, # right margin b=5, # bottom margin t=0 # top margin ), mapbox=dict( accesstoken=mapbox_key, bearing=0, style='mapbox://styles/max-schrader/ck8t1cmmc02wk1it9rv28iyte', center=go.layout.mapbox.Center( lat=33.12627, lon=-87.54891 ), pitch=0, zoom=14.1, ), coloraxis=log_color_axis if sum else color_axis ) sliders = [ { "currentvalue": { "font": colorbar_font, "prefix": "Time: ", "visible": True, "xanchor": "right" }, "pad": {"b": 10, "t": 20}, "len": 0.9, "x": 0.1, "y": 0, "visible": True, "steps": [ { "args": [[f.name], {"frame": {"duration": animation_step_duration, "redraw": True}, "mode": "immediate", "transition": {"duration": animation_step_duration}} ], "label": f.name, "method": "animate", } for f in fig_dict['frames'] ], } ] # noinspection PyTypeChecker fig_dict["layout"]["updatemenus"] = [ { "buttons": [ { "args": [None, {"frame": {"duration": animation_step_duration, "redraw": True}, "fromcurrent": True, "transition": {"duration": animation_step_duration, "easing": "linear"} } ], "label": "▶", # play symbol "method": "animate", }, { "args": [[None], {"frame": {"duration": 0, "redraw": False}, "mode": "immediate", "transition": {"duration": 0}}], "label": "◼", # pause symbol "method": "animate", }, ], "direction": "left", "pad": {"r": 10, "t": 20}, "type": "buttons", "x": 0.1, "y": 0, } ] fig_dict["layout"]["sliders"] = sliders fig = go.Figure(fig_dict) #fig.update_xaxes(showline=True, linewidth=2, linecolor='black', mirror=True) #fig.update_yaxes(showline=True, linewidth=2, linecolor='black', mirror=True) # return fig_dict return fig
import plotly.express as px fig = px.density_mapbox(df, lat='Latitude', lon='Longitude', z='Magnitude', radius=10, center=dict(lat=0, lon=180), zoom=0, mapbox_style="stamen-terrain") fig.show() # In[ ]: import pandas as pd quakes = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv') import plotly.graph_objects as go fig = go.Figure(go.Densitymapbox(lat=quakes.Latitude, lon=quakes.Longitude, z=quakes.Magnitude, radius=10)) fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=180) fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) fig.show() # In[ ]: import plotly.express as px df = px.data.gapminder().query("year == 2007") fig = px.line_geo(df, locations="iso_alpha", color="continent", # "continent" is one of the columns of gapminder projection="orthographic") fig.show()
import csv import pandas orenetes = pandas.read_csv('orenetes.csv',sep='\t',error_bad_lines=False) import plotly.graph_objects as go fig = go.Figure(go.Densitymapbox(lat=orenetes.decimalLatitude, lon=orenetes.decimalLongitude, z=orenetes.individualCount, radius=30)) fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=180) fig.update_layout(margin={"r":0, "t":o, "l":0, "b":0}) fig.show()
fig.add_trace( go.Scattermapbox( lat=est['lat'], lon=est['lng'], mode='markers', marker=go.scattermapbox.Marker(size=14, color='black', symbol='circle'), text=['Santo Amaro'], )) fig.add_trace( go.Densitymapbox( lat=label.lat, lon=label.lng, z=[1] * label.shape[0], radius=5, # colorscale = 'Reds', colorscale='Blues', reversescale=True, opacity=1, showscale=False)) fig.update_layout( hovermode='closest', mapbox=dict( accesstoken=mapbox_access_token, bearing=0, center=go.layout.mapbox.Center( lat=est.iloc[-1, 1], lon=est.iloc[-1, 2], ), # style='outdoors',
fig.add_trace( go.Scattermapbox(lat=centroids[:, 0], lon=centroids[:, 1], mode='markers', marker=go.scattermapbox.Marker( size=10, color='rgb(255, 0, 0)', ))) fig.update_layout(mapbox_style="open-street-map") fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) fig.show() fig = go.Figure( go.Densitymapbox( lat=df.Latitude, lon=df.Longitude, z=df.index, radius=1, )) fig.update_layout(mapbox_style="open-street-map") fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) fig.show() import seaborn as sns sns.jointplot(x=df["Latitude"], y=df["Longitude"], kind='kde', color="grey", space=0) sns.jointplot(x=df["Latitude"], y=df["Longitude"], kind='kde',
def display(self, metric, zmin=None, zmax=None): if not isinstance(self.masked_results, pd.DataFrame): self._preprocess_database_results() unique_times = self.masked_results.drop_duplicates( subset=["start_time_utc", "end_time_utc"]) t_min_ticks = unique_times["start_time_utc"] t_max_ticks = unique_times["end_time_utc"] t_min_labels = [x.strftime("%I%p, %d %b %y") for x in t_min_ticks] t_max_labels = [x.strftime("%I%p, %d %b %y") for x in t_max_ticks] global_min = self.masked_results[metric].min() global_max = self.masked_results[metric].max() zmin = global_min if zmin is None else zmin zmax = global_max if zmax is None else zmax start_time = unique_times["start_time_utc"].min() fig = go.Figure( data=go.Densitymapbox( lon=self.masked_results[self.masked_results["start_time_utc"] == start_time]["lon"], lat=self.masked_results[self.masked_results["start_time_utc"] == start_time]["lat"], z=self.masked_results[self.masked_results["start_time_utc"] == start_time][metric], colorscale="viridis", radius=100, opacity=0.5, showscale=True, zmin=global_min, zmax=global_max, colorbar={ "tickcolor": "white", "tickfont": { "color": "white" }, "title": { "text": "Score", "font": { "color": "white" } }, }, ), layout=go.Layout( title="{} to {}".format(t_min_labels[0], t_max_labels[0]), updatemenus=[ dict( type="buttons", buttons=[ dict(label="Play", method="animate", args=[None]), dict( label="Pause", method="animate", args=[ None, { "frame": { "duration": 0, "redraw": False }, "mode": "immediate", "transition": { "duration": 0 }, }, ], ), ], ), ], ), frames=[ go.Frame( data=[ go.Densitymapbox( lon=self.masked_results[ self.masked_results["start_time_utc"] == start_time + np.timedelta64(i, "h")]["lon"], lat=self.masked_results[ self.masked_results["start_time_utc"] == start_time + np.timedelta64(i, "h")]["lat"], z=self.masked_results[ self.masked_results["start_time_utc"] == start_time + np.timedelta64(i, "h")][metric], ) ], layout=go.Layout(title="{} to {}".format( t_min_labels[i], t_max_labels[i])), ) for i in range(0, len(t_min_labels)) ], ) fig.update_layout( mapbox_style="dark", mapbox_accesstoken=self.token, margin={ "l": 0, "r": 0, "b": 0, "t": 60 }, mapbox={ "center": { "lon": -0.09, "lat": 51.495 }, "zoom": 9.7 }, autosize=False, width=1600, height=900, paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)", # paper_bgcolor='black', title_font_color="white", ) fig.show() return {"max": zmax, "min": zmin}
def update_figure(selected_year,person_selected): filtered_df = location_data[location_data.year == selected_year] traces = [] lines = [] filtered_df=filtered_df[filtered_df.person.isin(person_selected)] filtered_people_df = location_data.copy(deep=True) filtered_people_df['location'] = filtered_people_df['latitude'].map(str) + filtered_people_df['longitude'].map(str) filtered_people_df.drop(['latitude', 'longitude'], axis=1, inplace=True) df_line = pd.DataFrame(filtered_people_df.groupby(['year','person'])['location'].nunique()).reset_index() for i in filtered_df.person.unique(): df_by_person= filtered_df[filtered_df['person'] == i] df_by_person_line = df_line[df_line['person'] == i] if i =='Leo': color_person='blue' elif i=='Pedro': color_person='purple' elif i=='Carolina': color_person='red' else: color_person='green' traces.append(dict(type='scattermapbox', mode="markers", lon = df_by_person['longitude'], lat = df_by_person['latitude'], marker=dict( size =10, # size=df_by_person.groupby(['longitude','latitude'])['datetime'].count(), sizeref=0.9, color=color_person, opacity=0.9), name=i, legendgroup =i ) ) lines.append(dict( x=df_by_person_line['year'], y=df_by_person_line['location'], mode='markers+lines', opacity=0.7, marker={ 'size': 5, 'line': {'width': 0.5, 'color': color_person} }, name=i )) fig = go.Figure(go.Densitymapbox(lat=filtered_df['latitude'], lon=filtered_df['longitude'], radius=10)) fig.update_layout(mapbox_style="stamen-terrain", mapbox_center_lon=180) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) return [{ 'data': traces, 'layout': dict(margin ={'l':0,'t':0,'b':0,'r':0}, mapbox = { 'center': {'lon': 10, 'lat': 10}, 'style': "stamen-terrain", 'center': {'lon': -20, 'lat': -20}, 'zoom': 1}, legend = dict(bordercolor='rgb(100,100,100)', borderwidth=2, itemclick='toggleothers', # when you are clicking an item in legend all that are not in the same group are hidden x=0.91, y=1) ) }, fig, { 'data': lines, 'layout': dict( xaxis={'title': 'Year'}, yaxis={'title': 'Locations'}, margin={'l': 40, 'b': 40, 't': 10, 'r': 10}, legend={'x': 0, 'y': 1} ) }]
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)