def display_mapc(df): px.set_mapbox_access_token( "pk.eyJ1IjoibXV5ZGlwYWxtYSIsImEiOiJjazk4eTI2ZmIwMjAzM2Vua3N0cHJhNXR6In0.y-fZg2ncJlXhVTAPO_9mmw") fig = px.scatter_mapbox(df, lat='longitud', lon='latitud', color='cc', hover_data=['punto_vacunacion'], hover_name='punto_vacunacion', center={'lon': df.loc[-1,'latitud'], 'lat': df.loc[-1,'longitud']}, zoom=13,labels={},width=800) return fig
def display_map(df): st.subheader(" Displaying Point based map") px.set_mapbox_access_token( "pk.eyJ1Ijoic2hha2Fzb20iLCJhIjoiY2plMWg1NGFpMXZ5NjJxbjhlM2ttN3AwbiJ9.RtGYHmreKiyBfHuElgYq_w" ) fig = px.scatter_mapbox(df, lat="Y", lon="X", color="METHOD", zoom=10) return fig
def make_figure(size, color): px.set_mapbox_access_token( "pk.eyJ1IjoiYmFucXVldGt1bWEiLCJhIjoiY2p0YjZ4bGJ2MGlseTN5bzlxcnlsbW8xNCJ9.udbxOpc2gZQcUX4m1VIqBg" ) return px.scatter_mapbox(GPS, lat="緯度 (°)", lon="経度 (°)", color=color, size=size, size_max=15, zoom=10, color_continuous_scale=px.colors.cyclical.IceFire, hover_name=size)
def display_map(df): st.subheader(" Displaying Point based map") px.set_mapbox_access_token( "pk.eyJ1Ijoic2hha2Fzb20iLCJhIjoiY2plMWg1NGFpMXZ5NjJxbjhlM2ttN3AwbiJ9.RtGYHmreKiyBfHuElgYq_w" ) fig = px.scatter_mapbox(df, lat="lat", lon="lon", color="district", size="confirmed", color_continuous_scale=px.colors.cyclical.IceFire, zoom=3, width=900, height=900) return fig
def kumapx(): px.set_mapbox_access_token( "pk.eyJ1IjoiYmFucXVldGt1bWEiLCJhIjoiY2p0YjZ4bGJ2MGlseTN5bzlxcnlsbW8xNCJ9.udbxOpc2gZQcUX4m1VIqBg" ) #mapboxのtokenを読み込む return px.scatter_mapbox( df, lat="Latitude", lon="Longtitude", color="Wait Time(min)", size="Wait Time(min)", size_max=60, zoom=10, #animation_frame="DATETIME", #animation_group="attractions", color_continuous_scale=px.colors.cyclical.IceFire, hover_name="attractions", title="Disney's Animal Kingdom Theme Park Wait Time from {} to {}". format(df["DATETIME"].min(), df["DATETIME"].max()))
def map_box_plot(df, locations): """ Generate a map box chart """ if len(locations) > 0: df = df[df['Capture Location'].isin(locations)] args = { 'lat': 'lat', 'lon': 'long', 'size': 'Annuli', 'color': 'Gender', 'size_max': 20, 'zoom': 10, } px.set_mapbox_access_token(environ['MAP_BOX']) fig = go.Figure(px.scatter_mapbox(df, **args)) fig['layout']['height'] = 600 graph = dcc.Graph(id='map-box-chart', figure=fig) return graph
def carto_clean(new_df, counties, communes): px.set_mapbox_access_token(open(".mapbox_token").read()) postal_code = pd.read_csv('population.csv') postal_code['Code Postal'] = postal_code['Code Postal'].astype('str') postal_code['Code Postal'] = postal_code['Code Postal'].str.replace( 'R', '0') postal_code['Code Département'] = postal_code['Code Département'].astype( 'str') postal_code['Code Département'] = postal_code[ 'Code Département'].str.replace('R', '0') form_presence = new_df[new_df['Code Postal'] != 'A DISTANCE'] form_presence['Code Postal'] = form_presence['Code Postal'].astype('str') form_presence_by_city = form_presence.groupby(["Ville", "Code Postal"]).count() form_presence_by_city = form_presence_by_city['Nom'] form_presence_by_city.name = 'Nombre de formations' form_presence_by_city = form_presence_by_city.reset_index() form_by_city = pd.merge(postal_code, form_presence_by_city, left_on=['Commune', 'Code Postal'], right_on=["Ville", "Code Postal"]) #st.write(form_presence_by_city[['Ville','Code Postal','Nombre de formations']][form_presence_by_city['Code Postal'].isin(form_by_city['Code Postal'])==False]) #st.write(form_presence_by_city[['Nombre de formations']][form_presence_by_city['Code Postal'].isin(form_by_city['Code Postal'])==False].sum()) form_by_city = form_by_city.dropna() form_by_dep = form_by_city.groupby('Code Département').sum().reset_index() form_by_dep = pd.merge(form_by_dep, communes, left_on='Code Département', right_on='Code Dept') return form_by_dep, form_by_city
def display_map(df): px.set_mapbox_access_token("pk.eyJ1Ijoic2hha2Fzb20iLCJhIjoiY2plMWg1NGFpMXZ5NjJxbjhlM2ttN3AwbiJ9.RtGYHmreKiyBfHuElgYq_w") fig = px.scatter_mapbox(df, lat='latitude', lon='longitude', zoom=10) return fig
import dash import dash_core_components as dcc import dash_html_components as html import plotly.graph_objs as go import plotly_express as px import pandas as pd import flask ########### Set up the chart px.set_mapbox_access_token( 'pk.eyJ1Ijoibmlja21jY2FydHkiLCJhIjoiY2pxemppMDZoMGJxeDQ0dDJ5OWxhcXA3dCJ9.k6cGbYHEbY2UDT-D6chFbw' ) fatalities = pd.read_csv('Data/fatalities_geocoded.csv') fatalities = fatalities.drop('Unnamed: 0', axis=1) test = fatalities.groupby( ['state', 'race', 'location', 'latitude', 'longitude'])['name'].count() test = test.reset_index() test = test.rename({'name': 'count'}, axis=1) test = test.sort_values('count', ascending=False) fig = px.scatter_mapbox(test, lat="latitude", lon="longitude", color="race", size="count", color_continuous_scale=px.colors.cyclical.IceFire, size_max=20, zoom=3,
group_id=item, value_deserializer=lambda x: loads(x.decode('utf-8'))) consumer.subscribe(item) consumers.append(consumer) print('created consumers') # create app external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets) print('initiated app') # setmapbox style # current script path scripty_path = os.path.dirname(os.path.realpath(__file__)) mapbox_access_token = 'pk.eyJ1IjoibXo4NiIsImEiOiJja2I5bWozeGgwZTJ0MnJwZjdtbHBjZjNxIn0.pSTk6D13HreCcxth26axeg' px.set_mapbox_access_token(mapbox_access_token) print('set map box') # sql connection engine = create_engine(sql_key.key, echo=False) print('set sql engine') app.layout = html.Div( html.Div([ html.H4('Traffic Live Update'), dcc.Graph(id='live-update-graph'), dcc.Interval( id='interval-component', interval=5 * 1000, # in milliseconds n_intervals=0) ]))
geometry=gpd.points_from_xy(df.X_from, df.Y_from)) gdf["geometry_to"] = [Point(xy) for xy in zip(gdf.X_to, gdf.Y_to)] gdf['line'] = gdf.apply( lambda row: LineString([row['geometry_to'], row['geometry']]), axis=1) line_gdf = gdf[["node_start", "node_end", "line"]].set_geometry('line') return line_gdf line_gdf = create_line_gdf(df) line_gdf.plot() start = df[df["node_start"] == start_node] end = df[df["node_end"] == end_node] px.set_mapbox_access_token( "pk.eyJ1IjoiamV4ZnJlZG8iLCJhIjoiY2twZW1nbm82MXluYjJubmx6endsN25tdyJ9.AR5KtIhw-_kDoe3NUahpHg" ) px.scatter_mapbox(df, lon="X_from", lat="Y_from", zoom=12) fig = px.scatter_mapbox(df, lon="X_from", lat="Y_from", width=800, height=400, zoom=12) fig.add_trace(px.line_mapbox(df, lon="X_from", lat="Y_from").data[0]) fig.data[1].marker = dict(size=15, color="red") fig.add_trace(px.scatter_mapbox(end, lon="X_from", lat="Y_from").data[0]) fig.data[2].marker = dict(size=15, color="green") fig.add_trace(px.line_mapbox(df, lon="X_from", lat="Y_from").data[0]) fig.show()
import pandas as pd import numpy as np import time import ast import webbrowser import googlemaps import gmplot import polyline import plotly_express as px from haversine import haversine from hdbscan import HDBSCAN with open(".secret.key", "r") as f: api_keys = ast.literal_eval(f.read().strip()) px.set_mapbox_access_token(api_keys["mapbox"]) gmaps = googlemaps.Client(key=api_keys["samesame_gmaps"]) def get_loc(query, current=True): """Initialize a location using one of two methods: ---------------- current = True: Use data from cell towers, WiFi, and GPS current = False: Ask the user for a starting location This can be a string (search google maps, be specific) or a latitude-longitude coordinate ---------------- returns a dictionary of the form: {'lat': 47.606269, 'lng': -122.334747}
def display_map(df): px.set_mapbox_access_token( "pk.eyJ1IjoibXV5ZGlwYWxtYSIsImEiOiJjazk4eTI2ZmIwMjAzM2Vua3N0cHJhNXR6In0.y-fZg2ncJlXhVTAPO_9mmw") fig = px.scatter_mapbox(df, lat='longitud', lon='latitud',hover_name='punto_vacunacion',hover_data=None,zoom=10) return fig
import pandas as pd import geopandas as gpd import plotly_express as px import matplotlib.pyplot as plt df = pd.read_csv('data/go_track_trackspoints_edited.csv') gdf = gpd.GeoDataFrame( df, geometry=gpd.points_from_xy(df.longitude, df.latitude)) px.set_mapbox_access_token('pk.eyJ1Ijoic2hha2Fzb20iLCJhIjoiY2plMWg1NGFpMXZ5NjJxbjhlM2ttN3AwbiJ9.RtGYHmreKiyBfHuElgYq_w') polygon = gpd.read_file('data/CENTERAREA.geojson') mask = (polygon.loc[0, 'geometry']) pip_mask_geofence = gdf.within(mask) gdf.loc[:,'geofence'] = pip_mask_geofence gdf['geofence'] = gdf['geofence'].replace({True: 'In', False: 'Out'}) print(gdf) fig = px.scatter_mapbox(gdf, lat='latitude_edit', lon='longitude_edit', color='type', size='track_id', animation_frame='time', animation_group='track_id', size_max=10, zoom=12, text='altitude', width=1200, height=800) fig.show()
title='''Weight vs height relation of the offenders ({} years old)'''.format(AGE), color='race', size='age', hover_data=['birth date', 'block'], hover_name="name") FIG_HISTO_AVG = px.histogram(CSV, x="race", y='age', color="race", title="Age average per race", histfunc='avg') px.set_mapbox_access_token( 'pk.eyJ1IjoiYmFwdGlzdGVhZGFtIiwiYSI6ImNrMmdwdmNncDByZWIzbG9lbTExMmY5YmkifQ.D7vXobtSiwy2Z-_OAtUoeQ' ) FIG_MAP = px.scatter_mapbox(CSV, lat="lat", lon="lon", title='Map of the offences', color="race", size="age", hover_name='name', hover_data=['birth date', 'block'], zoom=9) FIG_HISTO_1.update_layout(legend_orientation="h", legend=dict(x=-0.01, y=1.115)) FIG_HISTO_2.update_layout(legend_orientation="h", legend=dict(x=-0.01, y=1.1),
dinosaur, flight_of_passage, Expedition_Everest, kilimanjaro_safaris, Navi_River ]) #DateFrameを縦につなげる df = df.sort_values("DATETIME") #日付時刻順にソートしておく df = df.dropna(subset=["wait_time(actual)"]) #何故か"wait_time(actual)"列にNaNが残っているので、もう一回弾く df["Wait Time(min)"] = df["wait_time(actual)"] #"wait_time(actual)"列を"Wait Time(min)"列にコピーする px.set_mapbox_access_token( "pk.eyJ1IjoiYmFucXVldGt1bWEiLCJhIjoiY2p0YjZ4bGJ2MGlseTN5bzlxcnlsbW8xNCJ9.udbxOpc2gZQcUX4m1VIqBg" ) #mapboxのtokenを読み込む px.scatter_mapbox( df, lat="Latitude", lon="Longtitude", color="Wait Time(min)", size="Wait Time(min)", size_max=60, zoom=10, animation_frame="DATETIME", animation_group="attractions", color_continuous_scale=px.colors.cyclical.IceFire, hover_name="attractions",
def main(): st.sidebar.markdown("### Recommendation type") section = st.sidebar.selectbox('choose recommendation type', [ 'Pick a Value', 'Location based', 'Content based', 'Collaborative Filtering' ], key=1) #fig.update_layout(mapbox_style="dark") #fig.show() # if section == "Pick a Value": st.markdown("## How to get the most out of this platform") st.markdown( 'This platform contains 3 recommendation system models to recommend to you restaurants based on Yelp reviews in Toronto city' ) st.markdown( "- If you're a new user of this platform or in this city and you have never tried any restaurant around toronto, please select the **location based** recommender on the sidebar to get recommended top restaurants around where you are." ) st.markdown( "- If you want recommendations of restaurants similar to one you have previously visited and liked, please select **content-based** on the sidebar." ) st.markdown( "- If this isn't your first time using this platform and would like to get recommendations based on previous restaurants you have visited and rated please select the **collaborative filtering** option on the sidebar." ) #st.markdown("- If you just want to compare the ratings of different restaurants you have in mind, please select **Restaurant Analytics** on the sidebar.") st.subheader("Graphical Overview of Restaurants in Toronto City") px.set_mapbox_access_token( "pk.eyJ1Ijoic2hha2Fzb20iLCJhIjoiY2plMWg1NGFpMXZ5NjJxbjhlM2ttN3AwbiJ9.RtGYHmreKiyBfHuElgYq_w" ) fig = px.scatter_mapbox(business_data, lat="latitude", lon="longitude", color="stars", size='review_count', size_max=15, zoom=10, width=1000, height=700) st.plotly_chart(fig) if section == "Location based": st.subheader('Location Based Recommendation System') st.markdown("please enter your location") location = st.text_area('Input your location here') if location: URL = "https://geocode.search.hereapi.com/v1/geocode" api_key = 'ODfYgIX45wrL41qboC3F_z2hg8e5_ABJYi71Pu6o948' # Acquire from developer.here.com PARAMS = {'apikey': api_key, 'q': location} lat_long = LOC.get_location(URL, PARAMS) latitude = lat_long[0] longitude = lat_long[1] df = KM.location_based_recommendation(business_data, latitude, longitude) if st.sidebar.checkbox("Show data", False): st.write(df) st.markdown( "## Geographical Plot of Nearby Recommended Restaurants from " + location) px.set_mapbox_access_token( "pk.eyJ1Ijoic2hha2Fzb20iLCJhIjoiY2plMWg1NGFpMXZ5NjJxbjhlM2ttN3AwbiJ9.RtGYHmreKiyBfHuElgYq_w" ) fig = px.scatter_mapbox(df, lat="latitude", lon="longitude", zoom=10, width=1000, height=700, hover_data=[ 'name', 'latitude', 'longitude', 'categories', 'stars', 'review_count' ]) fig.add_scattermapbox(lat=[latitude], lon=[longitude]).update_traces( dict(mode='markers', marker=dict(size=15))) fig.update_layout(mapbox_style="dark") st.plotly_chart(fig) if section == 'Content based': st.subheader('Content based recommendation system') st.markdown( "please select a restaurant similar to the one you'd like to visit" ) restaurant = st.selectbox('select restaurant', toronto_data['name'].unique()) if restaurant: restaurant_recommendations = CT.content_based_recommendations( restaurant) restaurant1 = toronto_data[toronto_data['name'] == restaurant_recommendations[0]][[ 'name', 'categories', 'super_score' ]].groupby(['name', 'categories'], as_index=False).mean() restaurant2 = toronto_data[toronto_data['name'] == restaurant_recommendations[1]][[ 'name', 'categories', 'super_score' ]].groupby(['name', 'categories'], as_index=False).mean() restaurant3 = toronto_data[toronto_data['name'] == restaurant_recommendations[2]][[ 'name', 'categories', 'super_score' ]].groupby(['name', 'categories'], as_index=False).mean() restaurant4 = toronto_data[toronto_data['name'] == restaurant_recommendations[3]][[ 'name', 'categories', 'super_score' ]].groupby(['name', 'categories'], as_index=False).mean() restaurant5 = toronto_data[toronto_data['name'] == restaurant_recommendations[4]][[ 'name', 'categories', 'super_score' ]].groupby(['name', 'categories'], as_index=False).mean() rest_merged = pd.concat([ restaurant1.head(1), restaurant2.head(1), restaurant3.head(1), restaurant4.head(1), restaurant5.head(1) ]) st.write(rest_merged) # st.subheader('Collaborative Filtering recommendation system') # if restaurant: # collab_recommendations = content_based_recommendations(restaurant) # collab_recommendations = pd.DataFrame(data = restaurant_recommendations) # st.write(restaurant_recommendations) if section != 'Pick a Value': if st.sidebar.checkbox("Compare restaurants by sentiments", False): choice = st.sidebar.multiselect('Pick restaurants', toronto_data['name'].unique()) if len(choice) > 0: st.subheader("Breakdown restaurant by sentiment") fig_3 = make_subplots(rows=1, cols=len(choice), subplot_titles=choice) for i in range(1): for j in range(len(choice)): fig_3.add_trace(go.Bar( x=plot_sentiment(choice[j]).Sentiment, y=plot_sentiment(choice[j]).text, showlegend=False), row=i + 1, col=j + 1) fig_3.update_layout(height=600, width=800) st.plotly_chart(fig_3)
import pandas as pd import numpy as np import time import ast import webbrowser import googlemaps import gmplot import polyline import plotly_express as px from haversine import haversine from hdbscan import HDBSCAN with open('.secret.key', 'r') as f: api_keys = ast.literal_eval(f.read().strip()) px.set_mapbox_access_token(api_keys['mapbox']) gmaps = googlemaps.Client(key=api_keys['samesame_gmaps']) def get_loc(query, current=True): """Initialize a location using one of two methods: ---------------- current = True: Use data from cell towers, WiFi, and GPS current = False: Ask the user for a starting location This can be a string (search google maps, be specific) or a latitude-longitude coordinate ---------------- returns a dictionary of the form: {'lat': 47.606269, 'lng': -122.334747}