def route_animation(transport): #calculate the shortest G = ox.graph_from_place('Montpellier, France', network_type=transport) start = (43.61032245, 3.8966295) end = (43.61032245, 3.8966295) start_node = ox.get_nearest_node(G, start) end_node = ox.get_nearest_node(G, end) route = nx.shortest_path(G, start_node, end_node) #listing nodes and coordinates from the route node_start = [] node_end = [] X_to = [] Y_to = [] X_from = [] Y_from = [] length = [] for u, v in zip(route[:-1], route[1:]): node_start.append(u) node_end.append(v) length.append(round(G.edges[(u, v, 0)]['length'])) X_from.append(G.nodes[u]['x']) Y_from.append(G.nodes[u]['y']) X_to.append(G.nodes[v]['x']) Y_to.append(G.nodes[v]['y']) #create a data frame df = pd.DataFrame(list(zip(node_start, node_end, X_from, Y_from, X_to, Y_to, length, travel_time)), columns =["node_start", "node_end", "X_from", "Y_from", "X_to", "Y_to", "length", "travel_time"]) df.head() start = df[df["node_start"] == start_node] end = df[df["node_end"] == end_node] #animate the route with Plotly Express fig = px.scatter_mapbox(df, lon= "X_from", lat="Y_from", zoom=13, width=1000, height=800, animation_frame=df.index) fig.update_layout(mapbox_style="stamen-toner") fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) fig.data[0].marker = dict(size = 20, color="black") fig.add_trace(px.scatter_mapbox(start, 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.write_html("route_animation.html") fig.show()
def get_map(df_geo): # Map fig_map = px.scatter_mapbox(df_geo, lat="latitude", lon="longitude", animation_frame='date', animation_group='school', color="Category", size="total", color_discrete_sequence=px.colors.qualitative.Prism, center={"lat": 34.221749, "lon": -84.135526}, zoom=10, # height=00, # width=700, hover_name='school', hover_data=['school', 'total', 'F2F Students & Staff']) fig_map.update_layout(mapbox_style="carto-positron") fig_map.update_layout(margin={}, autosize=True, title=dict( text='Reported Positive Cases', font=dict( color='black', size=26), xanchor="center", x=0.5)) # fig_map['layout']['sliders'][0]['y'] = 1.2 # fig_map['layout']['updatemenus'][0]['y'] = 1.2 return fig_map
def update_graph_live(n): postgreSQL_select_Query = 'SELECT sensorid,time,lat,lon,signal from test WHERE ( unix_timestamp( ) - unix_timestamp( time ) ) < 10 GROUP BY CONCAT(sensorid, time) HAVING COUNT(*) = 1' cursor.execute(postgreSQL_select_Query) df = pd.read_sql_query(postgreSQL_select_Query, conn) #df = pd.DataFrame(cars, columns = ['time', 'lat','lon','signal']) #print(df) #print('ploting') # Create the graph with subplots figure = px.scatter_mapbox(df, lat='lat', lon='lat', color='lat', color_discrete_map={ "Red": "red", "Green": "green", "Orange": "orange" }, size_max=16, zoom=9) figure.update_layout( uirevision=True, mapbox={'center': { 'lon': -73.862614, 'lat': 40.799312 }}) print(df) print('to plot') return figure
def update_graph(xaxis_column_name): if xaxis_column_name == 'Hour': query = 'SELECT time, cam_ID, lat, lon, AVG(vehicles) as average_vehicles FROM traffic_cams WHERE time >= NOW() - INTERVAL 1 HOUR and mod(minute(time),5) = 0 GROUP BY CONCAT(cam_ID, time)' if xaxis_column_name == 'Day': query = 'SELECT time, cam_ID, lat, lon, AVG(vehicles) as average_vehicles FROM traffic_cams WHERE time >= NOW() - INTERVAL 24 HOUR and mod(minute(time),120) = 0 GROUP BY CONCAT(cam_ID, time)' if xaxis_column_name == 'Week': query = 'SELECT time, cam_ID, lat, lon, AVG(vehicles) as average_vehicles FROM traffic_cams WHERE time >= NOW() - INTERVAL 168 HOUR and mod(minute(time),840) = 0 GROUP BY CONCAT(cam_ID, time)' df2 = pd.read_sql(query, con=engine) df2['time_by_m'] = df2['time'].dt.floor('1Min') df2 = df2.drop_duplicates(['time_by_m', 'cam_ID']) df2['time_mark'] = df2['time_by_m'].astype(str) df2.sort_values(by='time') figure = px.scatter_mapbox( df2, lat='lat', lon='lon', color='average_vehicles', size='average_vehicles', color_continuous_scale=px.colors.sequential.Inferno, size_max=16, animation_frame='time_mark', animation_group='cam_ID', zoom=9) return figure
def update_graph_live(n): # build data frame for mapplot df = pd.read_sql( 'SELECT * FROM traffic_cams WHERE ( unix_timestamp( ) - unix_timestamp( time ) ) < 15 GROUP BY cam_ID HAVING COUNT(*) = 1;', con=engine) # df = pd.read_sql('SELECT time, cam_ID, lat, lon, AVG(vehicles) as average_vehicles FROM traffic_cams WHERE ( unix_timestamp( ) - unix_timestamp( time ) ) < 15 GROUP BY CONCAT(cam_ID, time)', con=engine) if len(df) < 10: df = pd.read_sql( 'SELECT * FROM traffic_cams WHERE ( unix_timestamp( ) - unix_timestamp( time ) ) < 60 GROUP BY cam_ID HAVING COUNT(*) = 1;', con=engine) # start plot #print(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) print(df) print('ploting') # Create the graph with subplots figure = px.scatter_mapbox( df, lat='lat', lon='lon', color='vehicles', size='vehicles', color_continuous_scale=px.colors.sequential.thermal, size_max=16, zoom=11) figure.update_layout( uirevision=True, mapbox={'center': { 'lon': -73.880274, 'lat': 40.836478 }}) return figure
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 update_graph_live(n): # build data frame for mapplot df = pd.read_sql( 'SELECT time, cam_ID, lat, lon, cars, trucks, AVG(vehicles) as average_vehicles FROM traffic_cams WHERE ( unix_timestamp( ) - unix_timestamp( time ) ) < 10 GROUP BY CONCAT(cam_ID, time) HAVING COUNT(*) = 1', con=engine) #print(df) #print('ploting') # Create the graph with subplots figure = px.scatter_mapbox( df, lat='lat', lon='lon', color='average_vehicles', size='average_vehicles', hover_data=['cars', 'trucks'], color_continuous_scale=px.colors.sequential.Inferno, size_max=16, zoom=9) figure.update_layout( uirevision=True, mapbox={'center': { 'lon': -73.862614, 'lat': 40.799312 }}) print(df) print('to plot') return figure
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 update_map(clickData, x_axis_dimension, y_axis_dimension): if clickData: # if the user has clicked the heatmap then #query map data spatial_data = GetSpatialBins(db_connection, x_filter=clickData['points'][0]['x'], y_filter=clickData['points'][0]['y'], x_dimension=x_axis_dimension, y_dimension=y_axis_dimension) # build map plot map_plot = px.scatter_mapbox( spatial_data, lat="LAT_BIN", lon="LON_BIN", color="COUNT", size="COUNT", color_continuous_scale=px.colors.sequential.Sunset, range_color=(spatial_data.COUNT.min(), spatial_data.COUNT.max()), size_max=15, zoom=10) # change setting to preserve map zoom and center on update map_plot.update_layout(uirevision=True) else: # If no data is selected then build a blank placeholder map to return #TODO: There must be a better way to create a blank maps\ # single point dataframe for placeholder map sample_data = pd.DataFrame(data={ 'LAT': [42.96], 'LON': [-85.67], 'COUNT': [5] }) # Build blank placeholder map map_plot = px.scatter_mapbox( sample_data, lat='LAT', lon='LON', color='COUNT', size='COUNT', size_max=1, color_continuous_scale=px.colors.sequential.Sunset, zoom=10) # change map style and padding settings map_plot.update_layout(mapbox_style="carto-positron", margin=dict(l=20, r=20, t=10, b=0)) return map_plot
def make_figure_box(size, feat): fig = px.scatter_mapbox( env, size=size, zoom=0.5, lat="Latitude [degrees North]", lon="Longitude [degrees East]", color=feat, hover_name="Marine_provinces", title=str(size) + " distribution and abundance (RPKG) on Tara Oceans.").for_each_trace( lambda t: t.update(name=t.name.replace(str(feat) + "=", ""))) fig.update_layout(plot_bgcolor="#F9F9F9", paper_bgcolor="#F9F9F9", titlefont={ "size": 20}) fig.update_layout(autosize=True) fig.update_yaxes(automargin=True) fig.update_layout(mapbox_style="open-street-map") 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 mapbox(df): """Plot the locations from a df containing ['lat', 'lng', 'name'] in an interactive window. """ zoom = autozoom(df) - 3 output = px.scatter_mapbox(df, lat='lat', lon='lng', hover_name=['name', 'rating'], zoom=zoom, color='label', width=600, height=600) return output
def update_graph_live(n): # build data frame for mapplot data = [] # read latest record from each consumer for consumer in consumers: #dummy poll consumer.poll() # go to end of the stream consumer.seek_to_end() for message in consumer: value = message.value data.append(value) if len(data) > 0: break # build df for ploting df = pd.DataFrame(data) # log which cams are missing #got_cams = df['cam_ID'].tolist() #missed_cams = list(set(all_cams) - set(got_cams)) #missed_cams_sr = ' '.join([str(elem) for elem in missed_cams]) df.insert(1, 'missed_cams', ' ', True) # save to database df.to_sql(name='traffic_cams', con=engine, if_exists='append', index=False) # start plot print(len(data)) print('ploting') # Create the graph with subplots figure = px.scatter_mapbox( df, lat='lat', lon='lon', color='vehicles', size='vehicles', color_continuous_scale=px.colors.sequential.thermal, size_max=15, zoom=11) figure.update_layout( uirevision=True, mapbox={'center': { 'lon': -73.884704, 'lat': 40.825355 }}) return figure
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 test_location_based(): test_coordinates = { 'latitude' : [36.1017316], 'longitude' : [-115.1891691], } user1 = pd.DataFrame(test_coordinates) recommend_restaurants(top_res_lv, user1.longitude, user1.latitude) # plot the locations of the restaurants and the user fig = px.scatter_mapbox(recommend_restaurants(top_res_lv, user1.longitude, user1.latitude), lat="latitude", lon="longitude", zoom=10, width=1200, height=800, hover_data= ['name', 'latitude', 'longitude']) fig2 = fig.add_scattermapbox( lat=user1["latitude"],lon= user1["longitude"]).update_traces(dict(mode='markers', marker = dict(size = 15)))
def update_map(criteria_value): if criteria_value == 'None': value = None else: value = str(criteria_value) fig = px.scatter_mapbox(CSV, lat="lat", lon="lon", title='Map of the offences', color=value, size="age", hover_name='name', hover_data=['birth date', 'block'], zoom=9) fig.update_layout(legend_orientation="h", legend=dict(x=-0.01, y=1.1)) return fig
def mapbox(df): """Plot the locations from a df containing ['lat', 'lng', 'name'] in an interactive window. """ zoom = autozoom(df) - 3 output = px.scatter_mapbox( df, lat="lat", lon="lng", hover_name=["name", "rating"], zoom=zoom, color="label", width=600, height=600, ) return output
def update_graph_live(n): # build data frame for mapplot data = [] #dummy poll #consumer.poll(timeout_ms=0, max_records=40, update_offsets=True) # go to end of the stream #consumer.seek_to_end() # build df for plot max_time = 4 start_time = time.time() for message in consumer: value = message.value data.append(value) if (time.time() - start_time) > max_time: break #if len(data) > 14: # break # build df for ploting df = pd.DataFrame(data) # log which cams are missing #got_cams = df['cam_ID'].tolist() #missed_cams = list(set(all_cams) - set(got_cams)) #missed_cams_sr = ' '.join([str(elem) for elem in missed_cams]) #df.insert(1, 'missed_cams',missed_cams_sr, True) #print(missed_cams) # save to database #df.to_sql(name='traffic_cams', con=engine, if_exists = 'append', index=False) # start plot print(len(data)) print('ploting') # Create the graph with subplots figure = px.scatter_mapbox(df, lat='lat', lon='lon', color='vehicles', size='vehicles', color_continuous_scale=px.colors.sequential.thermal, size_max=16, zoom=11) figure.update_layout(uirevision = True, mapbox = {'center': {'lon':-73.880274, 'lat': 40.836478}}) return figure
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 display_map(data, otherLst): local = [] for index, row in data.iterrows(): if row['Resource Name'] in otherLst: local.append( [row['Resource Name'], row['Longitude'], row['Latitude']]) df = pd.DataFrame(local, columns=['Resource Name', 'Longitude', 'Latitude']) fig = px.scatter_mapbox(df, lat=df['Latitude'], lon=df['Longitude'], hover_name=df["Resource Name"], hover_data=[df["Longitude"], df["Latitude"]], color_discrete_sequence=["fuchsia"], zoom=3, height=300) fig.update_layout(mapbox_style="open-street-map") fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) 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 browse(): token = 'pk.eyJ1IjoibWF6YWJkdWwiLCJhIjoiY2trMWh1aXRsMHJhMjJxbzU0eTYzbTI5ZiJ9.DIP735c0I4CbxFHmTtNBCw' df = pd.read_excel('personal-well-being-borough.xlsx', sheet_name='Summary - Mean Scores', skiprows=1) columns = [1, 27, 37, 38] df2 = df.iloc[list(range(0, 33)), columns] # select happiness df2 = df2.drop([0, 1]) df2 = df2.reset_index(drop=True) df2["2018/19.2"] = np.array(df2["2018/19.2"], dtype=np.float64) ukavg = df.iloc[[50], [27]] #uk avg hapiness ukavg = ukavg["2018/19.2"][50] df2["%Difference from AVG"] = df2["2018/19.2"] for i in range(len(df2["%Difference from AVG"])): df2["%Difference from AVG"][i] = ( 100 * (df2["%Difference from AVG"][i] - ukavg) / ukavg) df2.columns = [ "Area", "Happiness", "Latitude", "Longitude", "%Difference from AVG" ] fig = px.scatter_mapbox(df2, lat=df2.Latitude, lon=df2.Longitude, size="Happiness", hover_name="Area", hover_data=["Happiness", "%Difference from AVG"], color_discrete_sequence=["fuchsia"], color="%Difference from AVG", size_max=10, zoom=9, title="Happiness Rating per Borough") fig.update_layout(mapbox_style="dark", mapbox_accesstoken=token) fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) div = fig.to_html(full_html=False) return render_template('browse.html', div_placeholder=div)
def topArtistPerCity(): totalDf = pd.DataFrame(columns=[ 'Artist Name', 'Max Listeners', 'Location', 'lat', 'lng', 'artist Label' ]) maxCityDf = pd.DataFrame( columns=['Artist Name', 'Max Listeners', 'Location']) for item in myCursor3: artistName = item['name'] artistArray = item['artist']['cities'] for row in artistArray: artistListener = row['listeners'] artistLabel = row['streams'] artistCity = row['city'] lat = row['lat'] lng = row['lng'] totalDf.loc[len(totalDf)] = [ artistName, artistListener, artistCity, lat, lng, artistLabel ] totalDf = totalDf.sort_values(['Location', 'Max Listeners'], ascending=False) #.reset_index() totalDf = totalDf.groupby(['Location']).max().reset_index() #.mean() # print(totalDf) for row in totalDf.iterrows(): print(row) # px.set_mapbox_access_token(open(config.mapApiToken).read()) fig = px.scatter_mapbox(totalDf, lat="lat", lon="lng", hover_name="Location", hover_data=['artist Label'], color_discrete_sequence=["fuchsia"], zoom=3, height=300) fig.update_layout(mapbox_style="open-street-map") fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) fig.show()
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
def plot_cluster(): fig1 = px.scatter_mapbox(restaurant_lv, lat="latitude", lon="longitude", color="cluster", size='stars', hover_data= ['name', 'latitude', 'longitude'], zoom=10, width=1200, height=800)
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
# Recommended Stations: df_recommeded = pd.DataFrame() df_recommeded = df_alldata.loc[(df_alldata['STATION'] == '23 ST') | (df_alldata['STATION'] == '34 ST-HERALD SQ') | (df_alldata['STATION'] == '34 ST-PENN STA') | (df_alldata['STATION'] == '42 ST-PORT AUTH') | (df_alldata['STATION'] == '14 ST-UNION SQ') | (df_alldata['STATION'] == '14 ST') | (df_alldata['STATION'] == 'GRD CNTRL-42 ST') | (df_alldata['STATION'] == '86 ST')] # In[3]: # [PPT SLIDE 5]: 2D map view (spatial distribution) of all station locations fig = px.scatter_mapbox(df_alldata, lat='LAT', lon='LON', zoom=11) fig.update_traces(marker=dict(size=10)) fig.update_layout(mapbox_style="stamen-toner") fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0}) fig.show() # In[4]: # Subset of all stations with more than 500,000 total traffic over the dataset's time range: df_stations_gt500k = df_alldata.take( df_alldata.loc[df_alldata['TOT_IN_OUT'] >= 500000].index) # [PPT SLIDE 6]: Map of these stations: fig = px.scatter_mapbox(df_stations_gt500k, lat="LAT", lon="LON",
) 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, hover_name='location', opacity=.5) ########### Display the chart external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] server = flask.Flask(__name__) app = dash.Dash(__name__, server=server, external_stylesheets=external_stylesheets) app.title = "Police Shootings"
folium.CircleMarker([lat, lng], popup = label, radius = 2, color = colors).add_to(sanfrans_map) sanfrans_map # In[54]: # 컬러별로 보기가 어려운 관계로 다른 시각화 패키지 plotly를 활용해본다 import plotly_express as px fig = px.scatter_mapbox(train_1000, lat = train_1000["Y"], lon = train_1000["X"], color = train_1000["Category"], hover_name = train_1000["PdDistrict"], zoom = 10) fig.update_layout(mapbox_style = "open-street-map") fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0}) fig.show() # 시각화하며 얻은 사실 # # 지도를 시각화한다고 해서 한눈에 특정지역에 특정범죄가 많이 발생하는것을 바로 파악하기는 어렵다는 사실이다. # 이유는 상위권에 속한 범죄들이 보통 대부분의 지역에서도 상위권인 점(특정 범죄 제외)때문이다. # # 따라서 map을 통해서는 2가지를 파악해야 한다는 사실을 파악해볼 수 있었다 #
title= '<b>Number of Zones per State from 4th May</b><br>Specific to Lockdown 3.0', legend=legend, barmode='stack') fig.show() # ### <a id='test'> Testing Labs in India</a> # In[68]: df_lab = pd.read_csv('dataset/ICMRTestingLabsWithCoords.csv') fig = px.scatter_mapbox(df_lab, lat="latitude", lon="longitude", mapbox_style='streets', hover_name='lab', hover_data=['city', 'state', 'pincode'], zoom=2.5, size_max=15, title='COVID19 Testing Labs in India') # In[34]: def add_text(ax, fontsize=12): for p in ax.patches: x = p.get_bbox().get_points()[:, 0] y = p.get_bbox().get_points()[1, 1] ax.annotate('{}'.format(int(y)), (x.mean(), y), ha='center', va='bottom',