def plot_cities(city_list='all'): """Plotting cities from a list. if city_list = all, use all city in csv file """ csvname = 'city_stats/city_summary.csv' if city_list == 'all': city_list = get_all_processed_cities(csvname) longitudes = [] latitudes = [] frac_fr = [] frac_en = [] fcsv = open(csvname, 'a') for icity in city_list: igeofname = get_geofilename(icity, True) icity_info = get_city_stats(igeofname, icity) istr_en = float(icity_info['english']) istr_fr = float(icity_info['french']) ilong = icity_info['longitude'] ilat = icity_info['latitude'] longitudes.append(ilong) latitudes.append(ilat) frac_en.append(istr_en) frac_fr.append(istr_fr) for ilong, ilat, ifr, ien in zip(longitudes, latitudes, frac_fr, frac_en): imaxmkr = max(ifr, ien) imkrfactor = 30/imaxmkr plt.plot(ilong, ilat, 'ro', markeredgecolor='r', ms=int(imkrfactor*ien), alpha=0.35) plt.plot(ilong, ilat, 'bo', markeredgecolor='b', ms=int(imkrfactor*ifr), alpha=0.35) mplleaflet.show() raw_input('press enter when finished...')
def map_visits(visits): fig, ax = plt.subplots() last_lat = 0 last_lng = 0 first = True for visit_num, visit in visits.iterrows(): if visit['POI Name'] is not None: lat, lng = float(visit['POI Lat']), float(visit['POI Long']) # Only bother plotting if location has changed. if lat != last_lat and lng != last_lng: if first: first = False plt.plot(lng, lat, '.', color='r', ms=10) else: plot_arrow([last_lng, lng], [last_lat, lat], longlat_to_dist([last_lat, lat], [last_lng, lng]), color='b', lw=3) last_lat = lat last_lng = lng # Display the mapfile. mplleaflet.show(fig=ax.figure)
def map_visits_dict(visits): fig, ax = plt.subplots() last_lat = 0 last_lng = 0 last_date = None for visit in visits: lng, lat = float(visit['Long']), float(visit['Lat']) date = visit['Start Time'].strftime('%Y-%m-%d') if 'POI Name' in visit: dot_colour = 'g' else: dot_colour = 'gray' if date != last_date: day_colour = [ 0.8 * np.random.rand(), 0.8 * np.random.rand(), 0.8 * np.random.rand() ] plt.plot(lng, lat, '.', color=dot_colour, ms=10) else: plot_arrow([last_lng, lng], [last_lat, lat], longlat_to_dist([last_lat, lat], [last_lng, lng]), arrow_colour=day_colour, dot_colour=dot_colour, lw=3) last_lat = lat last_lng = lng last_date = date # Display the mapfile. mplleaflet.show(fig=ax.figure)
def get_history_stations_rainfall(input_date, limit=20): """Get a visualized history rainfall data of a certain number of stations on a certain date. Parameters ---------- input_date : str the date parameter, format: YYYY-MM-DD limit : int the number of stations to return Retruns ------- DataFrameGroupBy A DataFrameGroupBy object with datetime as the key """ stations = get_all_stations(limit=limit) stations["mean_value"] = stations.Station.apply( lambda x: get_station_mean(x, input_date)) stations["mean_class"] = stations.mean_value.apply(get_mean_class) stations_grouped = stations.groupby("mean_class") import mplleaflet color_map = { "High": 'ms', 'Medium': 'rs', 'Low': 'bs', 'Very Low': 'ys', 'Zero': 'gs' } for k, v in stations_grouped: plt.plot(v["Long"], v["Lat"], color_map[k]) mplleaflet.show() return stations_grouped
def show_blob_map(data_frame): gdf = generate_blob_clusters(data_frame) ax = gdf.geometry.plot(linewidth=2.0, color='red', edgecolor='red', alpha=0.5) mplleaflet.show(fig=ax.figure, tiles='cartodb_positron')
def Visualization3(tot_path, list_nodes, nodesDF): """ ARGUMENT: tot_path : list of nodes composing the shortest path (list of int) list_nodes : sequence of nodes that need to be visited in order (list of int) RETURN: visualize the shortest path on an interactive map (it opens a new tab in the browser) """ shortest_path_coords = nodesDF[nodesDF['Id Node'].isin(tot_path)] visit = nodesDF[nodesDF['Id Node'].isin(list_nodes)] lats = shortest_path_coords.Longitude.values longs = shortest_path_coords.Latitude.values lats_visit = visit.Longitude.values longs_visit = visit.Latitude.values fig, ax = plt.subplots(figsize=(12, 9)) if dist == 'd': ax.plot(longs, lats, 'orange', linewidth=1.5, marker=11, markersize=8) elif dist == 't': ax.plot(longs, lats, 'hotpink', linewidth=1.5, marker=11, markersize=8) else: ax.plot(longs, lats, 'c', linewidth=1.5, marker=11, markersize=8) ax.plot(longs[0], lats[0], 'gX', markersize=18) ax.plot(longs_visit, lats_visit, 'bo', markersize=10) ax.plot(longs[-1], lats[-1], 'ro', markersize=18) mplleaflet.show(fig=fig) # mplleaflet.show(fig=fig, path='map.html') return fig
def map(self, utm_fuse, utm_zone, mappath): fig = plt.figure() ax = plt.gca() a2 = self.mp.X[self.mp.Validador == 1] b2 = self.mp.Y[self.mp.Validador == 1] a = self.mp.X[self.mp.Validador2 == 1] b = self.mp.Y[self.mp.Validador2 == 1] pc = pd.DataFrame( map( lambda x: utm.to_latlon(a.tolist()[x], b.tolist()[x], utm_fuse, utm_zone), range(len(a)))) pc2 = pd.DataFrame( map( lambda x: utm.to_latlon(a2.tolist()[x], b2.tolist()[x], utm_fuse, utm_zone), range(len(a2)))) pt = pd.DataFrame( map( lambda x: utm.to_latlon(self.mp.X[x], self.mp.Y[x], utm_fuse, utm_zone), range(len(self.mp)))) ax.scatter(pt[1], pt[0], c='b') ax.scatter(pc2[1], pc2[0], c='y', s=30) critic = ax.scatter(pc[1], pc[0], c='r', s=30) labels = self.mp.RC2[self.mp.Validador2 == 1].astype(str).tolist() tooltip = mpld3.plugins.PointLabelTooltip(critic, labels=labels) mpld3.plugins.connect(fig, tooltip) mplleaflet.show(path=mappath)
def latlonplot(self, htmlfile, Cmap = "Reds"): ''' In the future, we should add in a color choice method...or a save the data method. We can always export the previous data, however. This isn't working so we might want to find a different way of doing this...Is there another way to export to a leaflet map? ''' y = np.asarray(self.lat.astype(float)).flatten().tolist() x = np.asarray(self.lon.astype(float)).flatten().tolist() Order=np.asarray(self.resolvedtree[:,-1]).astype(int).flatten() # It might be better to reorder this elsewhere! y = [y[i] for i in Order] x = [x[i] for i in Order] name = np.asarray(self.name).flatten().tolist() s = [3000*n for n in self.timeinplace] myfig = plt.figure() mypic = myfig.add_subplot(111) mypic.scatter(x, y, c=s, s=s, cmap=Cmap) for i, txt in enumerate(name): mypic.annotate(name[i], (x[i], y[i])) mplleaflet.show(fig = myfig, path = htmlfile)
def main (): data = Data() demand = data.get_demand() waiting = data.get_waiting() distances = data.get_distances() crime = data.get_crime() # plt.plot(demand['lon'], demand['lat'], 'rs', label="demand points") # plt.plot(waiting['lon'].astype(np.float64), waiting['lat'].astype(np.float64), 'bs', label="waiting points") # plt.legend() # plt.show() # mplleaflet.show() distances['in_range'] = (distances['distance'] <= RADIUS).astype(int) distances = distances[ distances['WPname'] != 'Holland Park'] distances = distances[ distances['in_range'] == 1] unique_wp = distances['WPname'].unique() unique_wp = [unique_wp[60]] unique_dp = distances [ distances['WPname'] == unique_wp[0] ]['DAuid'] demand = demand[demand['DAuid'].isin(unique_dp)] waiting = waiting[waiting['name'].isin(unique_wp)] plt.plot(demand['lon'], demand['lat'], 'rs') plt.plot(waiting['lon'].astype(np.float64), waiting['lat'].astype(np.float64), 'bs') mplleaflet.show()
def showPathGraph(self, path): x, y = [], [] for p in path: x.append(p[0]) y.append(p[1]) fig = plt.figure() plt.plot(x, y) mplleaflet.show(fig=fig)
def show_blob_map(data_frame): gdf = generate_blob_clusters(data_frame) ax = gdf.geometry.plot(linewidth=2.0, color='red', edgecolor='red', alpha=0.5) # plt.show() mplleaflet.show(fig=ax.figure)
def generate_map(data_name: str, op_name: str) -> None: data = pd.read_pickle(data_name) fig, ax = plt.subplots() ax.scatter(data["longtitude"], data["latitude"], c=data["accidents"], cmap="jet") mplleaflet.show(fig=fig, path=op_name)
def execute_medical_AI(medical): joined = medical.join(medical.set_index('city'), lsuffix='_caller', on='city') if (joined.empty): print("Sorry no popular medical facilties found in your city") else: joined['distance'] = joined.apply(distance, axis=1) joined = joined[joined['distance'] < 1000] joined['count'] = joined.groupby(['lat_caller', 'lon_caller' ])['tags'].transform('count') joined = joined[joined['count'] > 10] if (joined.empty): print("Sorry no popular medical facilties found in your city") else: suggested = pd.DataFrame() suggested = joined suggested = suggested.drop_duplicates( subset=['lat_caller', 'lon_caller']) f = open("medical facilties suggessstion.txt", "w") f.write( 'Suggested medical facilties info you can find more than 10 medical facilties related amenities within 1Km\n' ) print(suggested['address_caller']) try: f.write(suggested['address_caller'].to_string()) except KeyError: f.write("Null") f.close() long_info = pd.DataFrame() long_info['Suggested medical facilties info'] = joined[ 'address_caller'] long_info['Chain_medical_facilties_Within_1KM'] = joined['amenity'] print() print("Other chain medical facilties info") print(long_info) plt.figure(figsize=(8, 6)) fig = plt.figure() plt.scatter(joined['lon_caller'], joined['lat_caller'], 30) plt.scatter(joined['lon'], joined['lat'], 10) filtered = lowess(joined['lat_caller'], joined['lon_caller'], frac=0.7) plt.plot(filtered[:, 0], filtered[:, 1], 'r-', linewidth=5) print( "Please see the map with blue dot is the suggessted medical facilties and orange dot is the nearby related amenities red line is your optimal waliking" ) print() mplleaflet.show(fig=fig)
def show_concave_hull_map(data_frame, buffer=20.0): clusters = np.unique(data_frame['Cluster'].values) polygons = list() cluster_numbers = list() for cluster in clusters: # Filter out the cluster points points_df = data_frame.loc[data_frame['Cluster'] == cluster, ['Longitude', 'Latitude']] # Get the underlying numpy array points = np.unique(points_df[['Longitude', 'Latitude']].values, axis=0) print("Cluster {0}: ({1})".format(cluster, points.shape[0])) # Create the concave hull object print(len(points)) concave_hull = ConcaveHull(points) # Calculate the concave hull array hull_array = concave_hull.calculate() if hull_array is not None: hull = asPolygon(hull_array) buffered_hull = concave_hull.buffer_in_meters(hull, buffer) # write_line_string("simple/simple_hull_{0}".format(cluster), hull) # write_line_string("buffer/buffer_hull_{0}".format(cluster), buffered_hull) polygons.append(buffered_hull) cluster_numbers.append(cluster) else: print("Failed to create concave hull for cluster {0}".format( cluster)) arr = np.unique(data_frame.loc[data_frame['Cluster'] == cluster, ['Longitude', 'Latitude']].values, axis=0) df = pd.DataFrame(data=arr, columns=['Longitude', 'Latitude']) df['Index'] = np.arange(df['Longitude'].count()) df.to_csv("data/failed_hull_{0}.csv".format(cluster), index=False) # Create a pandas data frame to store the concave hull polygons polygon_df = pd.DataFrame.from_dict(data={ 'cluster': cluster_numbers, 'polygon': polygons }) # polygon_df.to_csv("data/out/final_clusters.csv", index=False, quoting=csv.QUOTE_NONNUMERIC) # Create the GeoPandas data frame to display on the map polygon_gdf = gpd.GeoDataFrame(polygon_df, geometry='polygon') polygon_gdf.crs = {'init': 'epsg:4326'} ax = polygon_gdf.geometry.plot(linewidth=2.0, color='red', edgecolor='red', alpha=0.5) mplleaflet.show(fig=ax.figure, tiles='cartodb_positron')
def plot_geolocation_2(gps_points_1, gps_points_2): (lon1, lat1) = gps_points_1 (lon2, lat2) = gps_points_2 fig, ax = plt.subplots() ax.scatter(lon1, lat1, s=15, c='red', marker='v', alpha=0.4) ax.scatter(lon2, lat2, s=20, c='blue', marker='o', alpha=0.4) mplleaflet.show() return
def crime_by_location(): url = "https://phl.carto.com/api/v2/sql?q=" radius = my_entry.get() # in meters query = "SELECT * FROM incidents_part1_part2 WHERE ST_DWithin(the_geom::geography," \ "ST_GeographyFromText('POINT(-75.155351200 39.981193500)'), " + str(radius) + ")" # by gps coordinate df = pd.DataFrame(requests.get(url + query).json()['rows']) print(len(df)) plt.scatter(df.point_x, df.point_y, marker='o') # Draw red squares mplleaflet.show()
def plot_path(self, path): #This plot the path on OSM. x = [] y = [] for p in path: x.append(p[0]) y.append(p[1]) fig = plt.figure() plt.plot(x, y) mplleaflet.show(fig=fig)
def plt_selection(infile, outfile): src_lng, src_lat = load_sources_data(infile) trg_lng, trg_lat = load_targets_data(infile) center_lng, center_lat = load_center_data(infile) # plt.hold(True) plt.plot(src_lng, src_lat, 'b.') plt.plot(trg_lng, trg_lat, 'g.') plt.plot(center_lng, center_lat, 'r.') mplleaflet.show(path=outfile)
def generic_plot(file: str, title: str, out_file: str): """Creates a dynamic HTML map from the lat/lon and labels columns.""" data = pd.read_csv(file) fig = plt.figure(figsize=(20, 20)) plt.scatter(data.longitude, data.latitude, cmap=plt.cm.brg, c=data.labels, s=10) plt.xlabel('Longitude') plt.ylabel('Latitude') plt.title(title) plt.tight_layout() mplleaflet.show(fig, path=out_file)
def colored_ticket_map(ticket_data, address_data, streetvolume): """Function to plot volume maps, while coloring streets using colormap. We'll also add tickets if you user requests. Parameters ---------- ticket_data : dataframe merged ticket data Returns ------- matplotlib chart chart of volume and tickets """ print('Creating Ticket Map') colordict = { 'STR CLEAN': 'cyan', 'RES/OT': 'green', 'MTR OUT DT': 'red', 'DRIVEWAY': 'orange', 'DBL PARK': 'blue' } print(colordict) choice = int(input('How many tickets would you like to add?')) choice2 = input( 'Would you like to project the address data onto the street?(Y or N)') if choice > 0: df = ticket_data.sample(n=choice) df['color'] = df['ViolationDesc'].apply( lambda x: colordict.get(x, 'magenta')) colors = df['color'] geometry = [Point(xy) for xy in zip(df.lon, df.lat)] df = df.drop(['lon', 'lat'], axis=1) crs = {'init': 'epsg:4326'} gdf = gpd.GeoDataFrame(df, crs=crs, geometry=geometry) if choice2 == 'Y': print('Projecting Addresses to Street') gdf['geometry'] = gdf.progress_apply(lambda x: project_to_line( x['lineid'], streetvolume, x['geometry']), axis=1) ax = gdf.plot(marker="*", color=colors, markersize=2) filename = (map_loc + 'ColorTicketMap.html') try: os.remove(filename) except: pass mplleaflet.show(fig=ax.figure, crs=gdf.crs, tiles='cartodb_positron', path=filename) return
def run(self) -> None: self._difference_series = self._get_difference_series() self._print_cities_on_console() plt.figure() self._plot_target_cities() self._plot_cities() self._data_handler.close() mplleaflet.show()
def plot_model(numticks): """Function to plot a map, coloring the street based on the model fitted value. Parameters ---------- numticks : int number of tickets to plot on the map Returns ------- html map """ print('Loading Data') df = pd.read_sql_query( "Select t1.address, lat, lon, lineid from ticket_data t1 join address_data t2 on " " t1.address = t2.address where ViolationDESC = 'RES/OT' and lineid > 0 Limit + " + str(numticks), conn) print('Loading final model') with open(proc_loc + 'FinalModel.pkl', 'rb') as handle: model = pickle.load(handle) streetvolume = gpd.read_file(proc_loc + 'final_streets/SF_Street_Data.shp') model = model[['lineid', 'fitted']] streetdf = streetvolume.merge(model, left_on='lineid', right_on='lineid') streetdf['fitted'] = -1 * streetdf['fitted'] print('Creating Map of model') choice2 = input( 'Would you like to project the address data onto the street?(Y or N)') streetdf = streetdf.to_crs(epsg=4326) streetdf.sort_values(by='fitted', ascending=False, inplace=True) streetdf.reset_index(inplace=True) ax = streetdf.plot(column='index', cmap='RdYlGn', alpha=1) geometry = [Point(xy) for xy in zip(df.lon, df.lat)] df = df.drop(['lon', 'lat'], axis=1) crs = {'init': 'epsg:4326'} gdf = gpd.GeoDataFrame(df, crs=crs, geometry=geometry) if choice2 == 'Y': print('Projecting Addresses to Street') gdf['geometry'] = gdf.apply(lambda x: project_to_line( x['lineid'], streetvolume, x['geometry']), axis=1) gdf.plot(ax=ax, marker="*", color='black', markersize=3) filename = (map_loc + 'ModelMap.html') try: os.remove(filename) except: pass mplleaflet.show(fig=ax.figure, crs=streetvolume.crs, tiles='cartodb_positron', path=filename) return
def imprimir_solicitudes(self): plt.figure(figsize=(8, 6)) fig = plt.figure() for usuario in self.__usuarios: for solicitud in usuario.get_solicitudes(): latitud_origen = solicitud["origen"]["latitud"] longitud_origen = solicitud["origen"]["longitud"] latitud_destino = solicitud["destino"]["latitud"] longitud_destino = solicitud["destino"]["longitud"] coordinates = [[longitud_origen, latitud_origen], [longitud_destino, latitud_destino]] self.create_route(coordinates) mplleaflet.show(fig=fig)
def map_POIs_by_num_visits(POIs): fig, ax = plt.subplots() for UID, POI in POIs.items(): plt.plot(float(POI['Long']), float(POI['Lat']), '.', color='b', alpha=0.3, ms=20 * np.log10(POI['# Visits'])) # Display the mapfile. mplleaflet.show(fig=ax.figure)
def main(): lat = [] lon = [] location_index = 0 while os.path.exists(PATH + str(location_index) + '.json'): with open(PATH + str(location_index) + '.json', "r") as f: data = json.loads(f.read()) lat.append(data["lat"]) lon.append(data["lon"]) location_index += 1 plt.plot(lon, lat, 'rs') mplleaflet.show()
def volume_maps(ticket_data, streetvolume): """Function to plot volume maps, while coloring streets using colormap. We'll also add tickets if you user requests. Parameters ---------- ticket_data : dataframe merged ticket data Returns ------- matplotlib chart chart of volume and tickets """ print('Creating Volume Map') choice = int(input('How many tickets would you like to add?')) choice2 = input( 'Would you like to project the address data onto the street?(Y or N)') times = ['am', 'pm', 'ev', 'ea'] for time in times: streetvolume['totalinv_' + time] = streetvolume['total_' + time].apply( lambda x: np.log(1 / (x + .5))) nhoods = gpd.read_file(raw_loc + 'AnalysisNeighborhoods.geojson') ax = streetvolume.plot(column='totalinv_ea', cmap='jet', alpha=1) if choice > 0: df = ticket_data.sample(n=choice) geometry = [Point(xy) for xy in zip(df.lon, df.lat)] df = df.drop(['lon', 'lat'], axis=1) crs = {'init': 'epsg:4326'} gdf = gpd.GeoDataFrame(df, crs=crs, geometry=geometry) if choice2 == 'Y': print('Projecting Addresses to Street') gdf['geometry'] = gdf.progress_apply(lambda x: project_to_line( x['lineid'], streetvolume, x['geometry']), axis=1) gdf.plot(ax=ax, marker="*", color='black', markersize=2) filename = (map_loc + 'VolumeMap.html') try: os.remove(filename) except: pass mplleaflet.show(fig=ax.figure, crs=streetvolume.crs, tiles='cartodb_positron', path=filename) return
def leaflet_plot_stations(binsize, hashid): df = pd.read_csv('./data/C2A2_data/BinSize_d{}.csv'.format(binsize)) station_locations_by_hash = df[df['hash'] == hashid] lons = station_locations_by_hash['LONGITUDE'].tolist() lats = station_locations_by_hash['LATITUDE'].tolist() plt.figure(figsize=(8, 8)) plt.scatter(lons, lats, c='r', alpha=0.7, s=200) # 在IDE里面触发显示, 如果在ipynb里面不需要这句 mplleaflet.show() return mplleaflet.display()
def show_path(graph, ref_dir, src, dst, algorithm=path_finder.ShortestPathAlgorithm.dijkstra, show_graph=False, show_entry_points=True): path = find_path(graph, ref_dir, src, dst, algorithm=algorithm) if path is None: raise read_shp.ShapeFileNavigatorException("path does not exist") if show_graph: color = 'blue' line_width = 5 else: color = (random.uniform(0, .5), random.uniform(0, .5), random.uniform(0, .5)) line_width = 2 x = list() y = list() for i in path: x.append(i[0]) y.append(i[1]) plt.plot(x, y, color=color, linestyle='solid', marker='o', linewidth=line_width) if show_graph is True: pos = path_finder.nx.get_node_attributes(graph, 'pos') path_finder.nx.draw(graph, pos, node_size=10) path_finder.nx.draw_networkx_labels(graph, pos, font_size=5, font_family='sans-serif') if show_entry_points is True: x_coordinates = [path[0][0], path[-1][0]] y_coordinates = [path[0][1], path[-1][1]] plt.scatter(x=x_coordinates, y=y_coordinates, color=color, marker='D') mplleaflet.show()
def main(): """Main function when used as a script.""" parser = argparse.ArgumentParser() parser.add_argument("directory") parser.add_argument("--activity", nargs="*") parser.add_argument("--since") parser.add_argument("--filter_outliers", action="store_true") args = parser.parse_args() files = [x for x in os.listdir(args.directory) if x.endswith(".gpx")] tracks = [] total_file_count = len(files) for k, file_name in enumerate(sorted(files)): file_name = os.path.join(args.directory, file_name) start_time = time.time() print("Reading file %d/%d: %s..." % ((k + 1), total_file_count, file_name), end="") sys.stdout.flush() file_tracks = read_gpx_file(file_name) for track in file_tracks: if args.since and track["time"] < iso8601_to_datetime(args.since): print("Skipping track, too old...", end="") continue if args.activity and track["type"][0] not in args.activity: print("Skipping track, wrong type (%r)..." % track["type"][0], end="") continue tracks.append(track) print("%.2f seconds" % (time.time() - start_time)) segments = [] for track in tracks: for segment in track["segments"]: segment["name"] = track["name"][0] segments.append(segment) tracks = None # Allow GC of all the data if args.filter_outliers: segments = filter_outliers(segments) fig = plot_segments(segments) segments = None # Allow GC of all the data print("Saving and opening in a browser (can take a couple of minutes)") sys.stdout.flush() mplleaflet.show(path="map-all.html", tiles="osm", fig=fig)
def generate_map(): conn = sql.connect("geocoordinates1.db") c = conn.cursor() x = c.execute("SELECT lon,lat FROM GeoCoordinates ") list_data = x.fetchall() x = [] y = [] for data in list_data: x.append(data[0]) y.append(data[1]) list_data = np.array(list_data) plt.plot(list_data[:, 0], list_data[:, 1]) list_data = rdp(list_data, epsilon=1e-4) fig = plt.figure() plt.plot(list_data[:, 0], list_data[:, 1], "r*") mplleaflet.show()
def show_route(self): ''' Plots a cycle in the graph that starts at a given point. ''' import matplotlib.pyplot as plt import mplleaflet plt.plot(self.begin.lon, self.begin.lat, 'ro') plt.plot(self.lons, self.lats, 'b') return mplleaflet.show()
def plot_stations(longitudes, latitudes, embedded = False): if embedded: plt.figure(figsize = (8, 8)) plt.scatter(longitudes, latitudes, c = 'b', marker = 'D', alpha = 0.7, s = 200) return mplleaflet.display() if embedded else mplleaflet.show()
features = [feat for feat in gj['features'][::10]] xy = np.array([feat['geometry']['coordinates'] for feat in features]) # Transform the data to EPSG:26986 (Mass. state plane) proj_in = pyproj.Proj(preserve_units=True, init='epsg:4326', no_defs=True) crs_out = {'init': 'epsg:26986', 'no_defs': True} proj_out = pyproj.Proj(preserve_units=True, **crs_out) xy = np.array([pyproj.transform(proj_in, proj_out, c[0], c[1]) for c in xy]) # Grab the speed (m/s) speed = np.array([feat['properties']['speed'] for feat in features]) # Grab the course. Course is 0 degrees due North, increasing clockwise course = np.array([feat['properties']['course'] for feat in features]) angle = np.deg2rad(-course + 90) # Convert to angle in xy plane # Normalize the speed to use as the length of the arrows r = speed / max(speed) uv = r[:, np.newaxis] * np.column_stack([np.cos(angle), np.sin(angle)]) # For each point, plot an arrow pointing in the direction of the iPhone's # course estimate. The arrow length is proportional to the phone's speed # estimate. For a bigger effect, color each other based on its speed plt.quiver(xy[:,0], xy[:,1], uv[:,0], uv[:,1], speed) root, ext = os.path.splitext(__file__) mapfile = root + '.html' # Create the map mplleaflet.show(path=mapfile, crs=crs_out, tiles=mplleaflet.maptiles.mapbox('jwass.gnj4hje6'))
df = df[df['globvalue'] > 0] # Setting the index, then calling unstack() creates the matrix of values # indexed by Hrapx in the columns, Hrapy in the rows. Try to do that in # MATLAB! df.set_index(['hrapy', 'hrapx'], inplace=True) df = df.unstack() # Sorting the values here is unnecessary, but do it just in case df.sort_index(axis=0, inplace=True) df.sort_index(axis=1, inplace=True) g = df['globvalue'] plt.contour(4762.5 * (g.columns.values - 401), 4762.5 * (g.index.values - 1601), g) # See http://www.nws.noaa.gov/oh/hrl/distmodel/hrap.htm # Note: The Proj.4 CRS definition below is gleaned from reading the NWS and # Proj.4 docs. Reach out if it's not correct although the resulting map looks # right. crs = {'lon_0': -105.0, 'lat_ts': 60.0, 'R': 6371200, 'proj': 'stere', 'units': 'm', 'lat_0': 90.0} root, ext = os.path.splitext(__file__) mapfile = root + '.html' mplleaflet.show(crs=crs, path=mapfile, tiles='mapbox bright')
def show_map(self): '''Shows map :return: ''' mplleaflet.show()
features = [feat for feat in gj['features'][::10]] xy = np.array([feat['geometry']['coordinates'] for feat in features]) # Transform the data to EPSG:26986 (Mass. state plane) proj_in = pyproj.Proj(preserve_units=True, init='epsg:4326', no_defs=True) crs_out = {'init': 'epsg:26986', 'no_defs': True} proj_out = pyproj.Proj(preserve_units=True, **crs_out) xy = np.array([pyproj.transform(proj_in, proj_out, c[0], c[1]) for c in xy]) # Grab the speed (m/s) speed = np.array([feat['properties']['speed'] for feat in features]) # Grab the course. Course is 0 degrees due North, increasing clockwise course = np.array([feat['properties']['course'] for feat in features]) angle = np.deg2rad(-course + 90) # Convert to angle in xy plane # Normalize the speed to use as the length of the arrows r = speed / max(speed) uv = r[:, np.newaxis] * np.column_stack([np.cos(angle), np.sin(angle)]) # For each point, plot an arrow pointing in the direction of the iPhone's # course estimate. The arrow length is proportional to the phone's speed # estimate. For a bigger effect, color each other based on its speed plt.quiver(xy[:,0], xy[:,1], uv[:,0], uv[:,1], speed) root, ext = os.path.splitext(__file__) mapfile = root + '.html' # Create the map mplleaflet.show(path=mapfile, crs=crs_out, tiles=('https://api.mapbox.com/styles/v1/jwasserman/cir51iqda0010bmnic1s5sb71/tiles/256/{z}/{x}/{y}?access_token=pk.eyJ1Ijoiandhc3Nlcm1hbiIsImEiOiJjaW9kNnRiaXUwNGh0dmFrajlqZ25wZnFsIn0.CU4YynqRJkmG1PwWDMBJSA', '<a href="https://mapbox.com/about/maps">© 2017 Mapbox</a> | <a href=https://www.openstreetmap.org/about">© OpenStreetMap</a>'))
import json import os import matplotlib.pyplot as plt import numpy as np import mplleaflet # Load up the geojson data filename = os.path.join(os.path.dirname(__file__), 'data', 'track.geojson') with open(filename) as f: gj = json.load(f) # Grab the coordinates (longitude, latitude) from the features, which we # know are Points xy = np.array([feat['geometry']['coordinates'] for feat in gj['features'][::10]]) # Plot the path as red dots connected by a blue line plt.hold(True) plt.plot(xy[:,0], xy[:,1], 'r.') plt.plot(xy[:,0], xy[:,1], 'b') root, ext = os.path.splitext(__file__) mapfile = root + '.html' # Create the map. Save the file to basic_plot.html. _map.html is the default # if 'path' is not specified mplleaflet.show(path=mapfile)