def plot_droughts_per_district(data, label_col='drought reported', district_col='District', path='../', country='Uganda', admin_level=1): droughts_per_district = data[[district_col, label_col ]].groupby(district_col).sum().reset_index() gdf_country = gpd.read_file(get_country_shapefile(path=path, country=country, admin_level=admin_level), crs='') gdf_country.rename(columns={'ADM1_EN': district_col}, inplace=True) gdf_country['centroid'] = gdf_country.centroid droughts_per_district = gdf_country[[district_col, 'geometry', 'centroid' ]].merge(droughts_per_district, on=district_col) droughts_per_district.set_geometry('centroid', drop=True, inplace=True) droughts_per_district = droughts_per_district[ droughts_per_district[label_col] > 0] geoplot.polyplot(gdf_country) ax = plt.gca() geoplot.pointplot(droughts_per_district, scale=label_col, color='darkred', marker='o', limits=(2, 14), legend=True, legend_values=[1, 3, 6, 9, 12], ax=ax) return
def test_polyplot(self): try: gplt.polyplot(series_gaussian_polys) gplt.polyplot(dataframe_gaussian_polys) finally: plt.close()
def plot_state_to_ax(state, ax): gplt.choropleth(tickets.set_index('id').loc[:, [state, 'geometry']], hue=state, cmap='Blues', linewidth=0.0, ax=ax) gplt.polyplot(nyc_boroughs, edgecolor='black', linewidth=0.5, ax=ax)
def test_subplots_global_projections(proj, countries): gplt.polyplot(countries, proj, ax=plt.subplot(2, 1, 1, projection=proj)).set_global() gplt.polyplot(countries, proj, ax=plt.subplot(2, 1, 2, projection=proj)).set_global() return plt.gcf()
def test_polyplot(self): try: gplt.polyplot(list_gaussian_polys, projection=gcrs.PlateCarree(), color='white') finally: plt.close()
def plot_state_to_ax(state, ax): """Reusable plotting wrapper.""" gplt.choropleth(tickets.set_index('id').loc[:, [state, 'geometry']], hue=state, projection=gcrs.AlbersEqualArea(), cmap='Blues', linewidth=0.0, ax=ax) gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(), edgecolor='black', linewidth=0.5, ax=ax)
def geopandas_map(): world = geopandas.read_file( geopandas.datasets.get_path('naturalearth_lowres')) boroughs = geopandas.read_file(geoplot.datasets.get_path('nyc_boroughs')) collisions = geopandas.read_file( geoplot.datasets.get_path('nyc_injurious_collisions')) geoplot.polyplot(world, figsize=(8, 4)) plt.savefig('world.jpg')
def parse_poly(lines): """ Parse an Osmosis polygon filter file. Accept a sequence of lines from a polygon file, return a shapely.geometry.MultiPolygon object. http://wiki.openstreetmap.org/wiki/Osmosis/Polygon_Filter_File_Format """ ring = None in_ring = False coords = [] for (index, line) in enumerate(lines): if index == 0: # first line is junk. continue elif index == 1: # second line is the first polygon ring. coords.append([[], []]) ring = coords[-1][0] in_ring = True elif in_ring and line.strip() == 'END': # we are at the end of a ring, perhaps with more to come. in_ring = False elif in_ring: #ADDED "list()" for python 3 # we are in a ring and picking up new coordinates. ring.append(list(map(float, line.split()))) elif not in_ring and line.strip() == 'END': # we are at the end of the whole polygon. break elif not in_ring and line.startswith('!'): # we are at the start of a polygon part hole. coords[-1][1].append([]) ring = coords[-1][1][-1] in_ring = True elif not in_ring: # we are at the start of a polygon part. coords.append([[], []]) ring = coords[-1][0] in_ring = True fig, ax = plt.subplots(figsize=(12, 10)) world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) pp = gplt.polyplot(world, ax=ax, zorder=1) poly = MultiPolygon(coords) shape = gpd.GeoDataFrame({'geometry': poly}, crs='epsg:3857') pp2 = gplt.polyplot(shape, zorder=0, ax=ax) # plt.plot(*poly.exterior.xy) plt.show() return MultiPolygon(coords)
def plot_footprints(products_gdf): world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) print(gpd.datasets.available) ax = gplt.polyplot(world, projection=gcrs.WebMercator()) gplt.polyplot(products_gdf, projection=gcrs.WebMercator(), edgecolor='r', ax=ax) plt.show() toto = 0
def _save_image(shape: gpd.GeoDataFrame, data: gpd.GeoDataFrame, output_file: str): fig, ax = plt.subplots(figsize=(6, 6)) gplt.polyplot(shape, ax=ax, zorder=1) gplt.pointplot(data, color="red", s=.5, ax=ax, zorder=2) shape_bounds = shape.total_bounds ax.set_ylim(shape_bounds[1], shape_bounds[3]) ax.set_xlim(shape_bounds[0], shape_bounds[2]) logging.info(f"Saving image to {output_file}") plt.savefig(output_file, bbox_inches='tight', pad_inches=0.1, dpi=300) # TODO: Solve "RuntimeWarning: More than 20 figures have been opened." plt.clf()
def plot_state_to_ax(state, ax): n = state_ticket_totals.loc[state]['Count'] gplt.choropleth(tickets_by_precinct(state), projection=gcrs.AlbersEqualArea(), cmap='Blues', linewidth=0.0, ax=ax) gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(), edgecolor='black', linewidth=0.5, ax=ax) ax.set_title("{0} (n={1})".format(state, n))
def produce_cont(index, path): ''' Function to produce simple contour maps of monthly location of turbulence events. Index refers to the month in question where 0 ==2018-11, 1==2018-12 etc. Will save as pngs into path directory ''' files = ['2018-11.csv', '2018-12.csv', '2019-01.csv', '2019-02.csv', '2019-03.csv', \ '2019-04.csv', '2019-05.csv', '2019-06.csv', '2019-07.csv', '2019-08.csv'] world_map_L1 = \ gpd.read_file('/home/dprice/Documents/ShapeFiles/GSHHS_shp/c/GSHHS_c_L1.shp') pn = '/home/dprice/Documents/CSV/' + files[index] datab = pd.read_csv(pn) crs = {'init': 'epsg:4326'} #coordinate reference system for lat lon geometry = [Point(xy) for xy in zip(datab['longitude'], datab['latitude'])] geo_db = gpd.GeoDataFrame(datab, crs=crs, geometry=geometry) ax = gplt.polyplot(world_map_L1, alpha=0.4, color='grey', figsize=(15, 15)) gplt.kdeplot(geo_db[geo_db['edr_peak_value'] > 0.12], ax=ax, \ facecolor='lightgray', cmap='Reds', shade=True, n_levels=30) ax.set_title(files[index][0:7]) outd = path + files[index][0:7] + '.png' plt.savefig(outd, format='png') return
def pretty_plot(gg: GeoDataFrame, islands: GeoDataFrame, poly_viewsheds: GeoDataFrame, save_figure_to: str, proj=PROJECTION): x = gg[gg.apply(lambda x: not x.is_empty and x.area > 1e-9)] xa = GeoDataFrame(x.centroid, geometry=0, crs=islands.crs) xa.columns = ['geometry'] xa_tmp = xa.reset_index() xa_tmp['idx'] = xa_tmp.apply(lambda y: (y.idx_a, y.idx_b), axis=1) xa_tmp['idx_other'] = xa_tmp.apply(lambda y: (y.idx_b, y.idx_a), axis=1) xa_tmp = xa_tmp.set_index('idx') paths = xa_tmp.join(xa_tmp, on='idx_other', lsuffix='_ab', rsuffix='_ba') paths = paths[paths.apply(lambda y: y.geometry_ab is not np.nan and y.geometry_ba is not np.nan, axis=1)] ax = gplt.polyplot( islands, projection=proj, figsize=(20, 20), color='darkgray' ) gplt.polyplot( poly_viewsheds, projection=proj, ax=ax, linewidth=0, facecolor='lightgray', alpha=0.3 ) gplt.polyplot( x, projection=proj, ax=ax, linewidth=0, facecolor='red', alpha=0.3 ) gplt.sankey( paths, start='geometry_ab', end='geometry_ba', ax=ax, projection=proj, alpha=0.05, rasterized=False ) plt.savefig(save_figure_to)
def run(map_dir_name, files): # europe = gpd.read_file('https://raw.githubusercontent.com/leakyMirror/map-of-europe/master/GeoJSON/europe.geojson') poland = gpd.read_file( 'https://gist.githubusercontent.com/filipstachura/391ecb779d56483c070616a4d9239cc7/raw' '/b0793391ab0478e0d92052d204e7af493a7ecc92/poland_woj.json') for file in files: print('Generating maps for: ' + file) geo_file = 'maps/geo/data/error_analysis/{file}.geojson'\ .format( dir_name=map_dir_name, file=file ) data = gpd.read_file(geo_file) print('Geo file loaded') for field in FIELDS: print('Generating map for: ' + field) prop = 'error_percentage_' + field for row in data.values: for val in row: if not isinstance(val, Polygon): if math.isnan(val): raise Exception('L:::') ax = geoplot.choropleth(data, hue=prop, cmap='YlOrRd', legend=True, edgecolor='lightgray', linewidth=0.0, scheme='fisher_jenks_sampled') ax2 = geoplot.polyplot(poland, figsize=(24, 16), ax=ax, edgecolor='black') plt.title('Pole: {field}, {title}'.format( field=field, title='Procent błędów > 2.0, pole: ')) path = 'D:\\workspace\\MGR\\maps\\{dir_name}\\{file}'\ .format(dir_name=map_dir_name, file=file) os.makedirs(name=path, exist_ok=True) fig = ax.get_figure() fig.savefig(path + '\\{field}.png'.format(field=field)) plt.close(fig) print('Maps generated')
def init(width, height, edgeColor, faceColor): boston = (-71.2, 42.2, -70.9, 42.4) boston_neighborhoods = gpd.read_file( 'datasets/Boston_Neighborhoods.geojson') return gplt.polyplot(boston_neighborhoods, extent=boston, edgecolor=edgeColor, facecolor=faceColor, figsize=(width, height))
def make_nysm_map(etime, time1, dropzeros=True): precip = [] for i in range(0, len(STN)): if (etime == 0): precip.append(np.nanmax(prcp_evol[i, 0])) else: precip.append(np.nanmax(prcp_evol[i, 0:etime])) if dropzeros: wh = [i for i, x in enumerate(precip) if x == 0.] for i in reversed( wh ): #needs to be reversed so we don't mess up the original indexing in the list del precip[i] del lons[i] del lats[i] del stns[i] nys = add_shape_coord_from_data_array() #plt.figure(figsize=(10,10)) ax = gplt.polyplot(nys, figsize=(8, 8), facecolor='None', edgecolor='black', projection=gcrs.LambertConformal()) levels = [ 0., 1., 2., 6., 10., 15., 20., 30., 40., 50., 70., 90., 110., 130., 150., 200., 300. ] norm = BoundaryNorm(levels, 16) c1 = ax.scatter(lons, lats, c=precip, norm=norm, marker='o', s=200, transform=ccrs.PlateCarree(), zorder=2, alpha=1., edgecolor='black', cmap=precip_colormap) ax.text(0.95, 0.01, 'Plot by L. Gaudet', verticalalignment='bottom', horizontalalignment='right', transform=ax.transAxes, color='grey', fontsize=10) cbar = plt.colorbar(c1, ticks=levels) cbar.set_label('Precipitation (mm)', rotation=90) plt.title( f'{str(time1.hour).zfill(2)} UTC {time1.day}-{time1.month}-{time1.year}', fontsize=18)
def run(): rectangles = gpd.read_file('geo/data/rectangles.geojson') europe = gpd.read_file( 'https://raw.githubusercontent.com/leakyMirror/map-of-europe/master/GeoJSON/europe.geojson' ) poland = gpd.read_file( 'https://gist.githubusercontent.com/filipstachura/391ecb779d56483c070616a4d9239cc7/raw' '/b0793391ab0478e0d92052d204e7af493a7ecc92/poland_woj.json') ax = geoplot.polyplot(europe, figsize=(24, 16), facecolor='white', edgecolor='black') ax2 = geoplot.polyplot(rectangles, ax=ax, edgecolor='lightgray') #plt.savefig("D:\workspace\MGR\\rectangles.png", bbox_inches='tight') #plot = ax2.plot() fig = ax2.get_figure() fig.savefig("D:\\workspace\\MGR\\rectangles.png")
def display_map2(gdf, clip, proj): # Setup the Voronoi axes; this creates the Voronoi regions ax = geoplot.voronoi( gdf, # Define the GeoPandas DataFrame hue='total_crimes', # df column used to color regions clip=clip, # Define the voronoi clipping (map edge) projection=proj, # Define the Projection legend=True, # Create a legend edgecolor='white', # Color of the voronoi boundaries ) # Render the plot with a base map geoplot.polyplot( chicago, # Base Map ax=ax, # Axis attribute we created above extent=chicago. total_bounds, # Set plotting boundaries to base map boundaries edgecolor='black', # Color of base map's edges linewidth=1, # Width of base map's edge lines zorder=1 # Plot base map edges above the voronoi regions )
def draw_month(month): to_full_month = { 'Jan': 'January', 'Feb': 'February', 'Mar': 'March', 'Apr': 'April', 'May': 'May', 'Jun': 'June', 'Jul': 'July' } frames = [] for i in range(1, 32): day_str = str(i) if i < 10: day_str = '0' + str(i) if os.path.exists(month + ' ' + day_str + '.csv'): df1 = pd.read_csv(month + ' ' + day_str + '.csv', header=None, names=[ 'id', 'longitude', 'latitude', 'location', 'created_at', 'lang' ]) frames.append(df1) df = pd.concat(frames) print(df.shape) mydict = dict(df.location.value_counts()) df['notnan'] = df['location'].notna() df['count'] = df.apply(lambda x: mydict[x.location] if x.notnan else 1, axis=1) df.drop_duplicates(subset='location', keep='first', inplace=True) gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.longitude, df.latitude)) scheme = mc.Quantiles(df['count'], k=5) world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) ax = gplt.polyplot( world, edgecolor='white', facecolor='lightgray', ) gplt.pointplot(gdf, ax=ax, hue='count', cmap='Reds', scale='count', scheme=scheme, legend=True, legend_var='hue') ax.set_title('Discussion on Twitter, ' + to_full_month[month], fontsize=10) plt.savefig(month + '.png', dpi=1000)
def run(map_dir_name, files): # europe = gpd.read_file('https://raw.githubusercontent.com/leakyMirror/map-of-europe/master/GeoJSON/europe.geojson') poland = gpd.read_file('https://gist.githubusercontent.com/filipstachura/391ecb779d56483c070616a4d9239cc7/raw' '/b0793391ab0478e0d92052d204e7af493a7ecc92/poland_woj.json') for file in files: print('Generating maps for: ' + file) geo_file = 'maps/geo/data/{dir_name}/{file}.geojson'\ .format( dir_name=map_dir_name, file=file ) data = gpd.read_file(geo_file) print('Geo file loaded') for field in FIELDS: for suffix in SUFFIXES: prop = field + suffix print('Generating map for: ' + prop) ax = geoplot.choropleth(data, hue=prop, cmap='YlOrRd', legend=True, edgecolor='lightgray', linewidth=0.0, scheme='fisher_jenks_sampled') ax2 = geoplot.polyplot(poland, figsize=(24, 16), ax=ax, edgecolor='black') plt.title('Pole: {field}, {title}'.format(field=field, title=TITLES[suffix])) path = 'D:\\workspace\\MGR\\maps\\{dir_name}\\{file}'\ .format(dir_name=map_dir_name, file=file) os.makedirs(name=path, exist_ok=True) fig = ax.get_figure() fig.savefig(path + '\\{prop}_ad.png'.format(prop=prop)) plt.close(fig) print('Maps generated')
def makePlotCase1(result_data, data_seoul, saveImg): log.info('[START] {}'.format('makePlotCase1')) result = None try: log.info('[CHECK] saveFile : {}'.format(saveImg)) crs = {'init': 'epsg:4162'} geometry = [Point(xy) for xy in zip(result_data["longitude"], result_data["latitude"])] geodata1 = gpd.GeoDataFrame(result_data, crs=crs, geometry=geometry) fig, ax = plt.subplots(figsize=(20, 20)) data_seoul['coords'] = data_seoul['geometry'].apply(lambda x: x.representative_point().coords[:]) data_seoul['coords'] = [coords[0] for coords in data_seoul['coords']] gplt.kdeplot(geodata1, cmap='rainbow', shade=True, alpha=0.5, ax=ax) gplt.polyplot(data_seoul, ax=ax) for idx, row in data_seoul.iterrows(): ax.annotate(s=row['sigungu_nm'], xy=row['coords'], horizontalalignment='center', size=15) fig = plt.gcf() plt.savefig(saveImg, dpi=600, bbox_inches='tight') plt.show() result = {'msg': 'succ'} return result except Exception as e: log.error("Exception : {}".format(e)) return result finally: # try, catch 구문이 종료되기 전에 무조건 실행 log.info('[END] {}'.format('makePlotCase1'))
def main(): data_dir = "./data/au-cities.csv" world = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres")) cities = gpd.read_file(gpd.datasets.get_path("naturalearth_cities")) print(world.head()) ax = gp.polyplot(world, projection = gp.crs.Orthographic()) ax.outline_patch.set_visible(True) #Graphs a choropleth of gdp / population gdp_per_person = world["gdp_md_est"] / world["pop_est"] scheme = mapclassify.Quantiles(gdp_per_person, k = 5) gp.choropleth(world, hue = gdp_per_person, scheme = scheme, cmap = "Greens") print(world.head()) #Graphs population size by establishing area size #to the African continent africa = world[world.continent == "Africa"] ax = gp.cartogram(africa, scale = "pop_est", limits = (0.2, 1), edgecolor = "black") gp.polyplot(africa, edgecolor = "black", ax = ax) plt.show()
def draw_per_day(date): if os.path.exists(date + '.csv') is False: return print(date) df = pd.read_csv(date + '.csv', header=None, names=[ 'id', 'longitude', 'latitude', 'location', 'created_at', 'lang' ]) print(date, df.shape) # assign count value mydict = dict(df.location.value_counts()) df['notnan'] = df['location'].notna() df['count'] = df.apply(lambda x: mydict[x.location] if x.notnan else 1, axis=1) df.drop_duplicates(subset='location', keep='first', inplace=True) gdf = gpd.GeoDataFrame(df, geometry=gpd.points_from_xy(df.longitude, df.latitude)) scheme = mc.Quantiles(df['count'], k=5) world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres')) ax = gplt.polyplot( world, edgecolor='white', facecolor='lightgray', ) gplt.pointplot(gdf, ax=ax, hue='count', cmap='Reds', scale='count', scheme=scheme, legend=True, legend_var='hue') ax.set_title('Discussion on Twitter, ' + date, fontsize=10) plt.savefig(date + '.png', dpi=1000)
def run(): rectangles = gpd.read_file('geo/data/rectangles.geojson') poland = gpd.read_file( 'https://gist.githubusercontent.com/filipstachura/391ecb779d56483c070616a4d9239cc7/raw' '/b0793391ab0478e0d92052d204e7af493a7ecc92/poland_woj.json') for region in REGIONS: ax = geoplot.choropleth(rectangles, hue=region, cmap='Purples', legend=False, edgecolor='lightgray', linewidth=0.0) ax2 = geoplot.polyplot(poland, figsize=(24, 16), ax=ax, edgecolor='black') fig = ax.get_figure() fig.savefig('D:\\workspace\\MGR\\maps\\regions\\{region}.png'.format( region=region)) plt.close(fig)
geom = gpd.GeoSeries( [Point(x, y) for x, y in zip(df_city.long.values, df_city.lat.values)]) df_city = gpd.GeoDataFrame(df_city, geometry=geom) #--------------------------------- (a)黑白沃罗诺伊图.---------------------------------------- ax1 = gplt.voronoi( df_city, #projection=gcrs.AlbersEqualArea(), clip=df_map, linewidth=0.5, #hue='orange', cmap='Reds',k=5, legend=False, edgecolor='k') ax2 = gplt.pointplot(df_city, color='white', s=10, edgecolors='k', ax=ax1) #zorder=2, gplt.polyplot(df_map, edgecolor='none', facecolor='lightgray', ax=ax1) #zorder=1, #plt.savefig('沃罗诺伊地图2.pdf') #--------------------------------- (b)彩色沃罗诺伊图.---------------------------------------- ax = gplt.voronoi( df_city, #projection=gcrs.AlbersEqualArea(), clip=df_map, hue='city', cmap='Set1', legend=True, k=10, edgecolor='w', alpha=0.75, legend_kwargs={ 'bbox_to_anchor': (1.15, 0.5), 'loc': 'center',
import geopandas as gpd import geoplot as gplt import geoplot.crs as gcrs import matplotlib.pyplot as plt import mapclassify as mc continental_usa_cities = gpd.read_file(gplt.datasets.get_path('usa_cities')) continental_usa_cities = continental_usa_cities.query('STATE not in ["AK", "HI", "PR"]') contiguous_usa = gpd.read_file(gplt.datasets.get_path('contiguous_usa')) scheme = mc.Quantiles(continental_usa_cities['POP_2010'], k=5) ax = gplt.polyplot( contiguous_usa, zorder=-1, linewidth=1, projection=gcrs.AlbersEqualArea(), edgecolor='white', facecolor='lightgray', figsize=(8, 12) ) gplt.pointplot( continental_usa_cities, scale='POP_2010', limits=(2, 30), hue='POP_2010', cmap='Blues', scheme=scheme, legend=True, legend_var='scale', legend_values=[8000000, 2000000, 1000000, 100000], legend_labels=['8 million', '2 million', '1 million', '100 thousand'],
intermittentLakes4 = classifiedData[(classifiedData['intermittent'] == 1)] print(intermittentLakes4.shape) lakeData5 = lakeData.copy() lakeData5['MeanAnnualAirTemp_c'] = lakeData['MeanAnnualAirTemp_c'] + 8 lakeData5['tmn'] = lakeData['tmn'] + 8 y_pred = dt.predict(lakeData5) classification = pd.DataFrame(data=y_pred, columns=['intermittent']) classifiedData = glakeData.copy() classifiedData['intermittent'] = classification['intermittent'].values intermittentLakes5 = classifiedData[(classifiedData['intermittent'] == 1)] print(intermittentLakes5.shape) #Plot current intermittent and annual lakes ax = gplt.polyplot(world, projection=gplt.crs.NorthPolarStereo(), facecolor='whitesmoke', figsize=(15, 15)) gplt.pointplot(annualLakes, color='black', ax=ax, s=0.5, label='Annual winter ice') gplt.pointplot(intermittentLakes, color='tab:orange', ax=ax, s=0.5, label='Intermittent winter ice') lgnd = plt.legend(loc="lower left", scatterpoints=1, fontsize=18) lgnd.legendHandles[0]._sizes = [100] lgnd.legendHandles[1]._sizes = [100]
import numpy as np import matplotlib.pyplot as plt import geoplot as gplt import geoplot.crs as gcrs import geopandas as gpd import scipy.stats as stats import descartes from shapely.geometry import Point, Polygon gun_df = pd.read_csv('./data/stage3.csv') clean_lat_long = gun_df[['n_killed', 'n_injured', 'longitude', 'latitude']].dropna() geometry = [ Point(xy) for xy in zip(clean_lat_long['longitude'], clean_lat_long['latitude']) ] crs = {'init': 'epsg:4326'} geo_df = gpd.GeoDataFrame(clean_lat_long, crs=crs, geometry=geometry) contiguous_usa = gpd.read_file(gplt.datasets.get_path('contiguous_usa')) ax = gplt.polyplot(contiguous_usa, projection=gcrs.AlbersEqualArea()) gplt.kdeplot(geo_df[geo_df['n_killed'] > 0], cmap='Reds', shade=True, thresh=0, clip=contiguous_usa, ax=ax) plt.show()
}) polyplot_kwargs = { 'projection': gcrs.AlbersEqualArea(), 'facecolor': (0.9, 0.9, 0.9), 'zorder': -100, 'linewidth': 0 } pointplot_kwargs = { 'projection': gcrs.AlbersEqualArea(), 'scale': 'ELEV_IN_FT', 'edgecolor': 'white', 'linewidth': 0.5, 'color': 'black' } ylim = (-1647757.3894385984, 1457718.4893930717) # Our first plot is a default linear-scale one. We can see from the results that this is clearly the most appropriate # one for this specific data. gplt.polyplot(contiguous_usa.geometry, ax=axarr[0][0], **polyplot_kwargs) gplt.pointplot(cities.query("POP_2010 > 10000"), ax=axarr[0][0], limits=(0.1, 10), **pointplot_kwargs) axarr[0][0].set_title("Linear Scale") axarr[0][0].set_ylim(ylim) # Next, a trivial identity scale. This results in a plot where every city has the same size. def identity_scale(minval, maxval): def scalar(val): return 2 return scalar gplt.polyplot(contiguous_usa.geometry, ax=axarr[0][1], **polyplot_kwargs) gplt.pointplot(cities.query("POP_2010 > 10000"), ax=axarr[0][1], scale_func=identity_scale, **pointplot_kwargs) axarr[0][1].set_title("Identity Scale") axarr[0][1].set_ylim(ylim)
import quilt from quilt.data.ResidentMario import geoplot_data import geopandas as gpd boroughs = gpd.read_file(geoplot_data.nyc_boroughs()) injurious_collisions = gpd.read_file(geoplot_data.nyc_injurious_collisions()) # A plot type using Voronoi tessellation: https://en.wikipedia.org/wiki/Voronoi_diagram import geoplot as gplt import matplotlib.pyplot as plt f, axarr = plt.subplots(1, 2, figsize=(16, 8)) gplt.voronoi(injurious_collisions.head(1000), edgecolor='lightsteelblue', linewidth=0.5, ax=axarr[0]) gplt.polyplot(boroughs, linewidth=0.5, ax=axarr[0]) gplt.voronoi(injurious_collisions.head(1000), hue='NUMBER OF PERSONS INJURED', cmap='Reds', edgecolor='white', clip=boroughs.geometry, linewidth=0.5, categorical=True, ax=axarr[1]) gplt.polyplot(boroughs, linewidth=1, ax=axarr[1]) axarr[0].axis('off') axarr[1].axis('off') plt.suptitle("Injurious Car Crashes in New York City, 2016", fontsize=20, y=0.95) plt.savefig("nyc-collisions-voronoi.png", bbox_inches='tight', pad_inches=0)
# Load the data (uses the `quilt` package). import geopandas as gpd from quilt.data.ResidentMario import geoplot_data boroughs = gpd.read_file(geoplot_data.nyc_boroughs()) collisions = gpd.read_file(geoplot_data.nyc_collision_factors()) # Plot the data. import geoplot.crs as gcrs import geoplot as gplt import matplotlib.pyplot as plt fig = plt.figure(figsize=(10,5)) ax1 = plt.subplot(121, projection=gcrs.AlbersEqualArea(central_latitude=40.7128, central_longitude=-74.0059)) gplt.kdeplot(collisions[collisions["CONTRIBUTING FACTOR VEHICLE 1"] == 'Failure to Yield Right-of-Way'], projection=gcrs.AlbersEqualArea(), shade=True, clip=boroughs.geometry, shade_lowest=False, ax=ax1) gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(), ax=ax1) plt.title("Failure to Yield Right-of-Way Crashes, 2016") ax2 = plt.subplot(122, projection=gcrs.AlbersEqualArea(central_latitude=40.7128, central_longitude=-74.0059)) gplt.kdeplot(collisions[collisions["CONTRIBUTING FACTOR VEHICLE 1"] == 'Lost Consciousness'], projection=gcrs.AlbersEqualArea(), shade=True, clip=boroughs.geometry, shade_lowest=False, ax=ax2) gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(), ax=ax2) plt.title("Loss of Consciousness Crashes, 2016") plt.savefig("nyc-collision-factors.png", bbox_inches='tight', pad_inches=0.1)
# Add a column we'll use later df['gdp_pp'] = df['gdp_md_est'] / df['pop_est'] boroughs = geopandas.read_file(geopandas.datasets.get_path('nybb')).to_crs(epsg='4326') injurious_collisions = geopandas.read_file( "https://github.com/ResidentMario/geoplot-data/raw/master/nyc-injurious-collisions.geojson") ############################################################################### # Plotting with Geoplot # ===================== # # We start out by replicating the basic GeoPandas world plot using Geoplot. import geoplot geoplot.polyplot(df, figsize=(8, 4)) ############################################################################### # Geoplot can re-project data into any of the map projections provided by # CartoPy (see the list # `here <http://scitools.org.uk/cartopy/docs/latest/crs/projections.html>`_). import geoplot.crs as gcrs ax = geoplot.polyplot(df, projection=gcrs.Orthographic(), figsize=(8, 4)) ax.set_global() ax.outline_patch.set_visible(True) ############################################################################### # ``polyplot`` is trivial and can only plot the geometries you pass to it. If # you want to use color as a visual variable, specify a ``choropleth``. Here # we sort GDP per person by country into five buckets by color.
}) polyplot_kwargs = { 'projection': gcrs.AlbersEqualArea(), 'facecolor': (0.9, 0.9, 0.9), 'zorder': -100, 'linewidth': 0 } pointplot_kwargs = { 'projection': gcrs.AlbersEqualArea(), 'scale': 'ELEV_IN_FT', 'edgecolor': 'white', 'linewidth': 0.5, 'color': 'black' } ylim = (-1647757.3894385984, 1457718.4893930717) # Our first plot is a default linear-scale one. We can see from the results that this is clearly the most appropriate # one for this specific data. gplt.polyplot(gpd.GeoSeries(continental_usa), ax=axarr[0][0], **polyplot_kwargs) gplt.pointplot(cities.query("POP_2010 > 10000"), ax=axarr[0][0], limits=(0.1, 10), **pointplot_kwargs) axarr[0][0].set_title("Linear Scale") axarr[0][0].set_ylim(ylim) # Next, a trivial identity scale. This results in a plot where every city has the same size. def identity_scale(minval, maxval): def scalar(val): return 2 return scalar gplt.polyplot(gpd.GeoSeries(continental_usa), ax=axarr[0][1], **polyplot_kwargs) gplt.pointplot(cities.query("POP_2010 > 10000"), ax=axarr[0][1], scale_func=identity_scale, **pointplot_kwargs) axarr[0][1].set_title("Identity Scale") axarr[0][1].set_ylim(ylim)
def test_fully_parameterized_global_projections(proj, countries): gplt.polyplot(countries, proj) ax = plt.gca() ax.set_global() return plt.gcf()
def test_basic_non_global_projections(proj, countries): gplt.polyplot(gpd.GeoDataFrame(geometry=[]), proj) # TODO: gplt.polyplot(countries, proj) return plt.gcf()
def test_basic_global_projections(proj, countries): gplt.polyplot(countries, proj) ax = plt.gca() ax.set_global() return plt.gcf()
provinces_gdf = gpd.GeoDataFrame({ 'provinceid': pids, 'provincename': pnames, 'geometry': ppoly, 'density': phdensity }) hotels_gdf = gpd.GeoDataFrame({ 'hotelname': hnames, 'geometry': hpoints, }) gplt.choropleth( provinces_gdf, hue='density', cmap='Purples', projection=gplt.crs.AlbersEqualArea(), legend=True, legend_kwargs={'orientation': 'horizontal'} ) plt.title("Hotel density by provinces in Armenia") plt.savefig('hotels_density_by_provinces.png', bbox_inches='tight') ax = gplt.kdeplot( hotels_gdf, clip=provinces_gdf.geometry, shade=True, shade_lowest=True, cmap='Reds', projection=gplt.crs.AlbersEqualArea() ) gplt.polyplot(provinces_gdf, ax=ax, zorder=1) plt.title("Hotels heatmap of Armenia") plt.savefig('hotels_heatmap.png', bbox_inches='tight')
import geopandas as gpd from quilt.data.ResidentMario import geoplot_data continental_cities = gpd.read_file(geoplot_data.usa_cities()).query('POP_2010 > 100000') continental_usa = gpd.read_file(geoplot_data.contiguous_usa()) # Plot the figure. import geoplot as gplt import geoplot.crs as gcrs import matplotlib.pyplot as plt poly_kwargs = {'linewidth': 0.5, 'edgecolor': 'gray', 'zorder': -1} point_kwargs = {'linewidth': 0.5, 'edgecolor': 'black', 'alpha': 1} legend_kwargs = {'bbox_to_anchor': (0.9, 0.9), 'frameon': False} ax = gplt.polyplot(continental_usa, projection=gcrs.AlbersEqualArea(central_longitude=-98, central_latitude=39.5), **poly_kwargs) gplt.pointplot(continental_cities, projection=gcrs.AlbersEqualArea(), ax=ax, scale='POP_2010', limits=(1, 80), hue='POP_2010', cmap='Blues', legend=True, legend_var='scale', legend_values=[8000000, 6000000, 4000000, 2000000, 100000], legend_labels=['8 million', '6 million', '4 million', '2 million', '100 thousand'], legend_kwargs=legend_kwargs, **point_kwargs) plt.title("Large cities in the contiguous United States, 2010") plt.savefig("largest-cities-usa.png", bbox_inches='tight', pad_inches=0.1)
# Shape the data. census_tracts = gpd.read_file("../data/boston_airbnb/Census2010_Tracts.shp") census_tracts = census_tracts.to_crs(epsg=4326) listings = pd.read_csv("../data/boston_airbnb/listings.csv") airbnbs = listings[['latitude', 'longitude']].apply(lambda srs: Point(srs['longitude'], srs['latitude']), axis='columns') listings = gpd.GeoDataFrame(data=listings, geometry=airbnbs) listings['price'] = listings['price'].map(lambda p: p[1:].replace(".", "").replace(",", "")).astype(float) listings = listings[['price', 'geometry']].dropna() boston_polygon = shapely.ops.cascaded_union(census_tracts.geometry.values) # Plot the data. # We're building a webmap, so we'll first create an unprojected map. ax = gplt.kdeplot(listings) gplt.polyplot(gpd.GeoSeries([boston_polygon]), edgecolor='white', linewidth=4, ax=ax) # Now we'll output this map to mplleaflet to generate our webmap. In this example we'll actually go one step further, # and use a non-default tile layer as well. The default mplleaflet webmap uses the default Leaflet tile service, # which is Open Street Map (OSM). OSM works great in a lot of cases, but tends to be very busy at a local level (an # actual strategic choice on the part of the OSM developers, as the higher visibility rewards contributions to the # project). # # Luckily Leaflet (and, by extension, mplleaflet) can be made to work with any valid time service. To do this we can use # the mplleaflet.fig_to_html method, which creates a string (which we'll write to a file) containing our desired # data. Here is the method signature that we need: # >>> mplleaflet.fig_to_html(<matplotlib.Figure>, tiles=(<tile url>, <attribution string>) # For this demo we'll use the super-basic Hydda.Base tile layer. # # For a list of possible valid inputs: # https://leaflet-extras.github.io/leaflet-providers/preview/
'facecolor': (0.9, 0.9, 0.9), 'zorder': -100, 'linewidth': 0 } pointplot_kwargs = { 'projection': gcrs.AlbersEqualArea(), 'scale': 'ELEV_IN_FT', 'edgecolor': 'white', 'linewidth': 0.5, 'color': 'black' } ylim = (-1647757.3894385984, 1457718.4893930717) # Our first plot is a default linear-scale one. We can see from the results that this is clearly the most appropriate # one for this specific data. gplt.polyplot(contiguous_usa.geometry, ax=axarr[0][0], **polyplot_kwargs) gplt.pointplot(cities.query("POP_2010 > 10000"), ax=axarr[0][0], limits=(0.1, 10), **pointplot_kwargs) axarr[0][0].set_title("Linear Scale") axarr[0][0].set_ylim(ylim) # Next, a trivial identity scale. This results in a plot where every city has the same size. def identity_scale(minval, maxval): def scalar(val): return 2 return scalar
# Load the data (uses the `quilt` package). from quilt.data.ResidentMario import geoplot_data import geopandas as gpd boston_zip_codes = gpd.read_file(geoplot_data.boston_zip_codes()) boston_zip_codes = boston_zip_codes.assign(id=boston_zip_codes.id.astype(float)).set_index('id') listings = gpd.read_file(geoplot_data.boston_airbnb_listings()) listings = listings.assign(zipcode=listings.zipcode.astype(float)) # Plot the data. import geoplot as gplt import geoplot.crs as gcrs import numpy as np import matplotlib.pyplot as plt ax = gplt.polyplot(boston_zip_codes.geometry, projection=gcrs.AlbersEqualArea(), facecolor='lightgray', edgecolor='gray', linewidth=0) gplt.aggplot(listings, projection=gcrs.AlbersEqualArea(), hue='price', by='zipcode', geometry=boston_zip_codes.geometry, agg=np.median, ax=ax, linewidth=0) ax.set_title("Median AirBnB Price by Boston Zip Code, 2016") plt.savefig("boston-airbnb-aggplot.png", bbox_inches='tight', pad_inches=0.1)