def test_choropleth(self, projection, hue_vars, legend_vars): kwargs = {'projection': projection} kwargs = {**kwargs, **hue_vars, **legend_vars} try: gplt.choropleth(gaussian_polys, **kwargs) finally: plt.close()
def plot_score_DMP_correlation(monitor_data, district_col='District', cmap='jet'): corrs = [] districts = [] grouped = monitor_data[[district_col, 'score', 'delta DMP']].dropna().groupby(district_col) for name, group in grouped: corrs.append(group[['score', 'delta DMP']].corr().values[0, 1]) districts.append(name) corr_data = pd.DataFrame() corr_data[district_col] = districts corr_data['Correlation'] = corrs corr_data = monitor_data[[district_col, 'geometry' ]].drop_duplicates().merge(corr_data, on=district_col) geoplot.choropleth(corr_data, hue=corr_data['Correlation'], cmap=cmap, legend=True) plt.title( r'Correlation between the drought score and normalized $\Delta$DMP') return corr_data
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 plotAll(self,figname): fig = plt.figure(figsize=(15, 15)) ax1 = plt.gca() tot_people =self._blocks["density"] scheme = mapclassify.Quantiles(tot_people, k=5) geoplot.choropleth( self._blocks, hue=tot_people, scheme=scheme, cmap='Oranges', figsize=(12, 8), ax=ax1 ) plt.savefig('density-'+figname) fig = plt.figure(figsize=(15, 15)) ax1 = plt.gca() ctx.plot_map(self._loc, ax=ax1) _c = ["red", "blue"] for i, _r in enumerate(self._roads): _r.plot(ax=ax1, facecolor='none', edgecolor=_c[i]) self._blocks.plot(ax=ax1,facecolor='none', edgecolor="black") plt.tight_layout() # Plot agents self.grid._agdf.plot(ax=ax1) plt.savefig('agents-'+figname)
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_choropleth(self): try: gplt.choropleth(dataframe_gaussian_polys, hue='hue_var', projection=gcrs.PlateCarree(), legend_kwargs={'fancybox': False}) finally: plt.close()
def update_choropleth(value): gdf = gpd.read_file(data_by_time) gdf_date = gdf[gdf['date'] == value] gplt.choropleth(gdf_date, hue='DMP_avg_normed') img = fig_to_uri(plt.gcf()) return img
def monitor_plot(monitor_data, monitor_date, date_col='date', label_col=None, cmap='jet'): month = monitor_date.month year = monitor_date.year select_date = date(year, month, 1).strftime("%Y-%m-%d") temp_1 = monitor_data[monitor_data[date_col] == select_date].copy() if (temp_1['score'].isna().sum() > 0) | (temp_1.empty): print('Data is not available.') return temp_2 = pd.DataFrame() if label_col is not None: temp_2 = temp_1.copy() temp_2['geometry'] = temp_2.centroid temp_2 = temp_2[temp_2[label_col]] norm = colors.Normalize(vmin=-0.6, vmax=0.6) if not temp_2.empty: temp_2.plot(marker='*', color='white', markersize=200, edgecolor="black", figsize=(6, 6)) ax = plt.gca() geoplot.choropleth(temp_1, hue=temp_1['score'], cmap=cmap, norm=norm, legend=True, ax=ax, zorder=0) else: geoplot.choropleth(temp_1, hue=temp_1['score'], cmap=cmap, norm=norm, legend=True, zorder=0, figsize=(6, 6)) plt.title(monitor_date.strftime("%B %Y")) return
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 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 plot_choropleth(gdf, parameter, title, cmap, outdir, country_iso3, filename, norm=None, use_scheme=False): fig, ax = plt.subplots() if use_scheme: try: scheme = mc.FisherJenks(gdf[parameter], k=5) except ValueError: logger.warning(f'Not enough values to plot {filename}') return 0 # Make nice legend labels if gdf[parameter].max() < 10: format_bin = lambda bin: f'{np.round(bin, 1)}' else: precision = len(str(int(scheme.bins[0]))) - 2 format_bin = lambda bin: f'{int(np.round(bin, -precision)):,}' legend_labels = [f'< {format_bin(scheme.bins[0])}'] + \ [f'{format_bin(scheme.bins[i] + 1)}–{format_bin(scheme.bins[i + 1])}' for i in range(len(scheme.bins) - 2)] + \ [f'> {format_bin(scheme.bins[-2])}'] legend_kwargs = ({'title': title}) else: scheme = None legend_labels = None legend_kwargs = ({ 'orientation': 'horizontal', 'label': title, 'shrink': 0.5 }) if norm is not None: norm = mpl.colors.Normalize(vmin=norm[0], vmax=norm[1]) gplt.choropleth(gdf, ax=ax, legend=True, lw=0.5, hue=parameter, cmap=cmap, legend_kwargs=legend_kwargs, scheme=scheme, legend_labels=legend_labels, norm=norm) fig.savefig(os.path.join(outdir, f'{country_iso3}_{filename}.png'), dpi=150) plt.close(fig)
def plot_vote(states, poll_avg): shapefile = 'cb_2018_us_state_5m/cb_2018_us_state_5m.shp' gdf = gpd.read_file(shapefile)[['NAME', 'geometry']] gdf.columns = ['name', 'geometry'] poll_avg_df = pd.DataFrame({'name': states, 'poll_avg': poll_avg}) data = gdf.merge(poll_avg_df, on='name', how='right') # data['poll_avg'].fillna(value=0) print(data) print(data['geometry']) scheme = mapclassify.Quantiles(data['poll_avg'], k=7) geoplot.choropleth(data, hue=data['poll_avg'], scheme=scheme, legend=True) plt.show() return
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 add_coa(option): #Get Bounds x0, x1 = ax.get_xlim() y0, y1 = ax.get_ylim() #Plot COA gplt.choropleth(coas, ax=ax, projection=geoplot.crs.WebMercator(), hue=option, zorder=1, alpha=0.7, scheme=mc.NaturalBreaks(coas[option], k=5), cmap=option, legend=False, edgecolor='lightgray') #Set Extent ax.set_xlim(left=x0, right=x1) ax.set_ylim(bottom=y0, top=y1)
def display_map3(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.choropleth( 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 produce_plot(self): df = gpd.GeoDataFrame(self.average_vote()) shapes = gpd.GeoDataFrame(self.redistricts) shapes.district += 1 shapes = shapes.set_index("district") df["geometry"] = shapes.geometry xmin = df.bounds.minx.min() xmax = df.bounds.maxx.max() ymin = df.bounds.miny.min() ymax = df.bounds.maxy.max() norm = mplc.Normalize(vmin=0.4,vmax=1) fig = plt.figure() if any("democrat" == df.party): ax = plt.subplot(111) ax = geoplot.choropleth(df[df.party == "democrat"], hue = "votes", norm = norm, cmap = "Blues", legend = True, ax = ax) if any("republican" == df.party): ax = geoplot.choropleth(df[df.party == "republican"], hue = "votes", norm = norm, cmap = "Reds", legend = True, ax = ax) ax.set_xbound(lower = xmin, upper = xmax) ax.set_ybound(lower = ymin, upper = ymax)
def plot_world_map(df): """ Plot a world map from a data frame """ cases_per_million = df['total_cases_per_million'] scheme = mapclassify.UserDefined( cases_per_million, bins=[100, 500, 1000, 5000, 10000, 15000, 20000]) gplt.choropleth( df, hue=cases_per_million, edgecolor='white', linewidth=1, scheme=scheme, cmap='Reds', legend=True, figsize=(12, 6), ) plt.title("Total Confirmed COVID-19 Cases Per Million as of 07-09-2020") # Without this, the world map doesnt load plt.show()
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 monitor_plot_dmp(monitor_data, monitor_date, date_col='date', cmap='jet'): month = monitor_date.month year = monitor_date.year select_date = date(year, month, 1).strftime("%Y-%m-%d") temp = monitor_data[monitor_data[date_col] == select_date].copy() temp = temp[['geometry', 'score', 'delta DMP']].dropna() if (temp.empty): print('Data is not available.') return f, axs = plt.subplots(1, 2, figsize=(13, 6)) norm1 = colors.Normalize(vmin=-0.6, vmax=0.6) geoplot.choropleth(temp, hue=temp['score'], cmap=cmap, norm=norm1, legend=True, ax=axs[0]) axs[0].title.set_text('score (' + monitor_date.strftime("%B %Y") + ')') norm2 = colors.Normalize(vmin=-0.6, vmax=0.6) geoplot.choropleth(temp, hue=temp['delta DMP'], cmap=cmap, norm=norm2, legend=True, ax=axs[1]) axs[1].title.set_text(r'normalized $\Delta$DMP (' + monitor_date.strftime("%B %Y") + ')') return
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 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)
def test_choropleth(self): try: gplt.choropleth(series_gaussian_polys, hue=list_hue_values) gplt.choropleth(dataframe_gaussian_polys, hue=list_hue_values) gplt.choropleth(dataframe_gaussian_polys, hue=list_hue_values) gplt.choropleth(dataframe_gaussian_polys, hue=series_hue_values) gplt.choropleth(dataframe_gaussian_polys, hue=map_hue_values()) gplt.choropleth(dataframe_gaussian_polys, hue='hue_var') finally: plt.close('all')
def test_choropleth(self): try: gplt.choropleth(series_gaussian_polys, hue=list_hue_values) gplt.choropleth(dataframe_gaussian_polys, hue=list_hue_values) gplt.choropleth(dataframe_gaussian_polys, hue=list_hue_values) gplt.choropleth(dataframe_gaussian_polys, hue=series_hue_values) gplt.choropleth(dataframe_gaussian_polys, hue=map_hue_values()) gplt.choropleth(dataframe_gaussian_polys, hue='hue_var') finally: plt.close('all')
geo_country = geo_data[geo_data["name"].str.lower() == country] # Finds the corresponding geo data # Obtain all the countries that receive litter from it countries, tons, percs = getCountriesStats(stat) geo_from_countries = geo_data[geo_data["name"].str.lower().isin( countries)] # Finds the corresponding geo data # gplt.polyplot(geo_country, figsize=(8, 4)) # gplt.polyplot(geo_from_countries, figsize=(8, 4)) # Note: this code sample requires gplt>=0.4.0. if len(tons) > 0 and len(geo_from_countries) == len(tons): scheme = mapclassify.Quantiles(tons, k=min(5, len(tons))) ax = gplt.polyplot(geo_data, figsize=(8, 4)) # ax = gplt.webmap(geo_data, projection=gcrs.WebMercator()) ax2 = gplt.choropleth(geo_from_countries, hue=tons, scheme=scheme, cmap='Greens', ax=ax) # gplt.choropleth(geo_country, hue=[1], cmap='gray', ax=ax2) plt.title(country.capitalize()) plt.show() else: print(F"------------- failed ------------") print(list(geo_from_countries["name"])) print(countries) exit() ## input_folder = config[GlobalModel.output_folder] input_file = config[GlobalModel.output_file]
"An exception has occured: there were not enough bins which contained buildings" ) continue rays = rays.drop(raysWithBuildings.index.values.tolist()) tree_list = list(rays['geometry']) + list(street['geometry']) strtree = STRtree(tree_list) pbf.accumulate_counts(strtree, street, 7) for k in street.index: grids[j].at[k, 'count'] = street.at[k, 'count'] if i < 10: # saves images of the plots of data for first 10 iterations ax = x.plot() scheme = mc.Quantiles(street['count'], k=20) gplt.choropleth(street, ax=ax, hue='count', legend=True, scheme=scheme, cmap="jet", legend_kwargs={'bbox_to_anchor': (1, 0.9)}) plt.savefig('../datasets_and_generators/ANN_trainimages/x_' + str(i) + '.png') plt.close() ''' part 4: concatenates data to MASTER training data files ATTENTION: when changing this file DO NOT immediately concatenate generated data to MASTER files, use a temporary json file by changing the file name below until it is certain that the data is compatible with the rest of the data set -compatibility involves: the data being the same shape (xpix & ypix), and that the format it is being saved in is consistent; refer to functions
how='inner', on='HUC_8') HUC8_Ecoregion = HUC8_Ecoregion.set_index('HUC_8', drop=True) NARS_NLA_FINAL = pd.concat([NARS_NLA_group_aux, HUC8_Ecoregion], ignore_index=False, sort=False) HUC8_NARS_NLA_FINAL = HUC8.merge(NARS_NLA_FINAL, on='HUC_8') proj = gcrs.AlbersEqualArea() norm = colors.LogNorm() #cmap = matplotlib.cm.viridis #cmap=matplotlib.cm.get_cmap() cmap.set_under('grey') gplt.choropleth( HUC8_NARS_NLA_FINAL, hue='PTL', projection=proj, norm=norm, cmap='viridis', k=5, scheme='quantiles', legend=True, legend_kwargs={'loc': 'lower right'}, figsize=(12, 12), vmin=0.8 ) #, vmin=0.8, vmax=HUC8_NARS_NLA_FINAL['PTL'].max() , linewidth=0.5, edgecolor='black',) plt.savefig('prueba6_1.pdf') plt.savefig("obesity.png", bbox_inches='tight', pad_inches=0.1)
q2 = gp.read_file('./Ookla shape data/2020q2') q3 = gp.read_file('./Ookla shape data/2020q3') q4 = gp.read_file('./Ookla shape data/2020q4') ma = gp.read_file('./data/export-gisdata.mapc.ma_municipalities').to_crs( epsg=4326) # In[57]: data_2020 = pd.concat([q1, q2, q3, q4]) # In[59]: ax = gplt.webmap(data_2020, projection=gcrs.WebMercator()) gplt.choropleth(data_2020, hue='avg_d_kbps', projection=gcrs.AlbersEqualArea(), cmap='Greens', legend=True, ax=ax) plt.show() # In[43]: # use the location of the centroid of each polygon data_2020['geometry'] = data_2020['geometry'].centroid # In[56]: ax = gplt.webmap(data_2020, projection=gcrs.WebMercator()) gplt.pointplot(data_2020, ax=ax, hue='avg_d_kbps', legend=True) plt.show()
HUC8['HUC_8'] = HUC8['HUC_8'].astype(int) HUC8.to_csv('HUC8.csv', index=False) HUC8_NARS_P = HUC8.merge(NARS_group_aux_filt_P, on='HUC_8') HUC8_NARS_P.to_csv('HUC8_NARS_P.csv', index=False) HUC8_NARS_N = HUC8.merge(NARS_group_aux_filt_N, on='HUC_8') HUC8_NARS_N.to_csv('HUC8_NARS_N.csv', index=False) proj = gcrs.AlbersEqualArea() norm = colors.LogNorm() gplt.choropleth(HUC8_NARS_P, hue='PTL', projection=proj, norm=norm, cmap='viridis', k=5, scheme='quantiles', legend=True, legend_kwargs={'loc': 'lower right'}, figsize=(12, 12)) plt.savefig('NARS_TP.pdf') plt.savefig("NARS_TP.png", bbox_inches='tight', pad_inches=0.1) proj = gcrs.AlbersEqualArea() norm = colors.LogNorm() gplt.choropleth(HUC8_NARS_N, hue='NH4', projection=proj, norm=norm, cmap='viridis', k=5,
############################################################################### # 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. geoplot.choropleth(df, hue='gdp_pp', cmap='Greens', figsize=(8, 4)) ############################################################################### # If you want to use size as a visual variable, you want a ``cartogram``. Here # are population estimates for countries in Africa. geoplot.cartogram(df[df['continent'] == 'Africa'], scale='pop_est', limits=(0.2, 1), figsize=(7, 8)) ############################################################################### # If we have data in the shape of points in space, we may generate a # three-dimensional heatmap on it using ``kdeplot``. This example also # demonstrates how easy it is to stack plots on top of one another. ax = geoplot.kdeplot(injurious_collisions.sample(1000), shade=True, shade_lowest=False,
def test_choropleth(self): try: gplt.choropleth(dataframe_gaussian_polys, hue='hue_var', projection=gcrs.PlateCarree(), legend_kwargs={'fancybox': False}) finally: plt.close()
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 import geoplot from plotnine import * world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres')) #-----------------------------Methods:plotnine----------------------------------------------- base_plot=(ggplot()+ geom_map(world, aes(fill='gdp_md_est'))+ scale_fill_distiller(type='seq', palette='reds')) print(base_plot) #-----------------------------Methods:geoplot----------------------------------------------- geoplot.choropleth( world, hue=world['gdp_md_est'],edgecolor='k', cmap='Reds',legend=True, figsize=(8, 4)) # Orthographic map projection ax = geoplot.polyplot( world, projection=geoplot.crs.Orthographic(central_longitude=90.0, central_latitude=0.0), figsize=(8, 4)) geoplot.choropleth( world, hue=world['gdp_md_est'], cmap='Reds',legend=True,edgecolor='k',ax=ax) ax.outline_patch.set_visible(True) #-------------------------Method:basemap--------------------------------------------------- from mpl_toolkits.basemap import Basemap import matplotlib.pyplot as plt import numpy as np
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))
gplt.polyplot( world, ax=ax, facecolor=missing_color, linewidth=0.05, ) gplt.choropleth( countries_gdf, # projection=gcrs.Robinson(), ax=ax, hue=countries_gdf['shdi'], scheme=scheme, cmap=cmap_world, legend_kwargs={ 'loc': 'lower left', 'fontsize': 10, 'frameon': True, 'edgecolor': background_color, 'facecolor': background_color }, linewidth=0.1, extent=(-180, -90, 180, 90), legend=True, ) plt.tight_layout() fig.show()
subplot_kw={ 'projection': gcrs.AlbersEqualArea(central_latitude=40.7128, central_longitude=-74.0059) }) # Educated f.suptitle('Comparison between Educated level and number of crimes', fontsize=16) f.subplots_adjust(top=0.95) gplt.choropleth(test_precincts, hue='Educated', projection=gcrs.AlbersEqualArea(central_latitude=40.7128, central_longitude=-74.0059), linewidth=0, figsize=(12, 12), scheme='Fisher_Jenks', cmap='Reds', legend=True, legend_kwargs={'loc': 'upper left'}, ax=axarr[0]) gplt.choropleth(test_precincts, hue='count', projection=gcrs.AlbersEqualArea(central_latitude=40.7128, central_longitude=-74.0059), linewidth=0, figsize=(12, 12), scheme='Fisher_Jenks', cmap='Blues', legend=True, legend_kwargs={'loc': 'upper left'},
# Load the data (uses the `quilt` package). import geopandas as gpd from quilt.data.ResidentMario import geoplot_data census_tracts = gpd.read_file(geoplot_data.ny_census_partial()) percent_white = census_tracts['WHITE'] / census_tracts['POP2000'] # Plot the data. import geoplot.crs as gcrs import geoplot as gplt import matplotlib.pyplot as plt gplt.choropleth(census_tracts, hue=percent_white, projection=gcrs.AlbersEqualArea(), cmap='Purples', linewidth=0.5, edgecolor='white', k=None, legend=True) plt.title("Percentage White Residents, 2000") plt.savefig("ny-state-demographics.png", bbox_inches='tight', pad_inches=0.1)