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 plot_dist(self, ax, sample=1000): for yr in self.yrs: yr_df = self.get_yr(yr) print (len(yr_df)) color = self.colors[yr] kdeplot(df=yr_df, ax=ax, shade=True, shade_lowest=False, n_levels=7) plt.xlim((-91.575, -91.52)) plt.ylim((41.645, 41.68))
def plot_gdf_kde(gdf, plotname, gridsize=300): ''' This function converts the lat/long distance into a meters distance. Parameters ---------- gdf: GeoDataFrame The dataframe used to generate the heatmap plotname: string Name of the save file for the plot gridsize: int The x, y size of the grid for the plot ''' gdf = gdf[gdf['count'] > 0] fig, ax = plt.subplots(figsize=(50, 50)) try: ax = gplt.kdeplot(gdf, shade=True, color="blue", figsize=(50, 50), gridsize=gridsize) except: print('Unable to plot kde for the following GeoDataFrame') print(gdf) #TODO Need to modify this to determine max lat/long ax.set_xlim(-74.0, -73.96) ax.set_ylim(40.7, 40.76) manhattan_buildings.plot(ax=ax, color="Black", figsize=(50, 50)) plt.savefig(plotname)
def test_kdeplot(self): # Just four code paths. try: gplt.kdeplot(gaussian_points, projection=None, clip=None) gplt.kdeplot(gaussian_points, projection=None, clip=gaussian_polys) gplt.kdeplot(gaussian_points, projection=gcrs.PlateCarree(), clip=gaussian_polys) gplt.kdeplot(gaussian_points, projection=gcrs.PlateCarree(), clip=gaussian_polys) finally: plt.close()
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'))
# 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)
############################################################################### # 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, clip=boroughs.geometry) geoplot.polyplot(boroughs, ax=ax) ############################################################################### # Alternatively, we may partition the space into neighborhoods automatically, # using Voronoi tessellation. ax = geoplot.voronoi(injurious_collisions.sample(1000), hue='NUMBER OF PERSONS INJURED', cmap='Reds', scheme='fisher_jenks', clip=boroughs.geometry, linewidth=0) geoplot.polyplot(boroughs, ax=ax)
# 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>)
import geopandas as gpd import geoplot as gplt import geoplot.crs as gcrs import matplotlib.pyplot as plt import mplleaflet # load the data boston_airbnb_listings = gpd.read_file( gplt.datasets.get_path('boston_airbnb_listings')) # we're building a webmap, so we'll first create an unprojected map. ax = gplt.kdeplot(boston_airbnb_listings) # 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/ # For the full fig_to_html method signature run mplleaflet.fig_to_html? in IPython or see further: # https://github.com/jwass/mplleaflet/blob/master/mplleaflet/_display.py#L26 fig = plt.gcf() with open("boston-airbnb-kde.html", 'w') as f:
df_huouse = gpd.GeoDataFrame(df_huouse, geometry=geom) #--------------------------------(a)点描法地图-------------------------------------------------- ax = gplt.pointplot(df_huouse, color='#54AEAD', s=3, edgecolors='none', figsize=(10, 6)) #projection=gcrs.AlbersEqualArea() gplt.polyplot(df_map, facecolor='white', edgecolor='k', ax=ax) #plt.savefig('热力地图1.pdf') #-------------------------------(b)二维核密度估计热力地图. --------------------------------------------------- ax = gplt.kdeplot( df_huouse, cmap='Spectral_r', shade=True, clip=df_map, #gridsize=100, figsize=(10, 6), cbar=True, cbar_kws={'shrink': 0.75}) #projection=gcrs.AlbersEqualArea() gplt.polyplot(df_map, facecolor='none', edgecolor='k', ax=ax, zorder=1) #plt.savefig('热力地图2.pdf') #-----------------------------Method:basemap-------------------------------------------------- from mpl_toolkits.basemap import Basemap import pandas as pd import matplotlib.pyplot as plt from matplotlib.patches import Polygon from matplotlib import cm, colors import numpy as np df_huouse = pd.read_csv("Virtual_huouse.csv")
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() # In[53]: ax = gplt.webmap(data_2020, projection=gcrs.WebMercator()) gplt.kdeplot(data_2020[['avg_d_kbps', 'geometry']], n_levels=50, cmap='Reds', thresh=0.05, shade=True, ax=ax) plt.show() # In[32]: gplt.choropleth(q1, hue='avg_d_kbps')
""" KDEPlot of Boston AirBnB Locations ================================== This example demonstrates a combined application of ``kdeplot`` and ``pointplot`` to a dataset of AirBnB locations in Boston. The result is outputted to a webmap using the nifty ``mplleaflet`` library. We sample just 1000 points, which captures the overall trend without overwhelming the renderer. `Click here to see this plot as an interactive webmap. <https://bl.ocks.org/ResidentMario/868ac097d671df1ed5ec83eed048560c>`_ """ import geopandas as gpd import geoplot as gplt import geoplot.crs as gcrs import matplotlib.pyplot as plt boston_airbnb_listings = gpd.read_file( gplt.datasets.get_path('boston_airbnb_listings')) ax = gplt.kdeplot(boston_airbnb_listings, cmap='viridis', projection=gcrs.WebMercator(), figsize=(12, 12), shade=True) gplt.pointplot(boston_airbnb_listings, s=1, color='black', ax=ax) gplt.webmap(boston_airbnb_listings, ax=ax) plt.title('Boston AirBnB Locations, 2016', fontsize=18)
gdf = geopandas.GeoDataFrame(new_data_reduced, geometry='Coordinates') if DEBUG==1: print(" Sample of the geospatial dataframe: \n", gdf.head()) # Convert from pandas data frame to a geopandas dataframe if DEBUG==1: print(" Boroughs sample :\n\n", boroughs.head() , "\n\n Collisions sample:\n\n" , collisions.head()) new_data_reduced.rename(columns={'Coordinates':'geometry'}, inplace='True') final_df = geopandas.GeoDataFrame(new_data_reduced) if DEBUG==0: print ('\n\nType of new data reduced: ',type(final_df)\ ,'\n\n Newly renamed columns of new_data_reduced :\n\n', final_df.head()) # Now making the geoplot of the plots with the #making the heatmap boroughs = geopandas.read_file(geoplot.datasets.get_path('nyc_boroughs')) ax = geoplot.kdeplot( final_df,# clip=boroughs.geometry, shade=True, cmap='Reds', projection=geoplot.crs.WebMercator()) geoplot.polyplot(boroughs, ax=ax, zorder=1) geoplot.webmap(boroughs,ax=ax,zoom=12) plt.show() # Trying to plot as point data over webmap instead of a heat map over a webmap ax = geoplot.webmap(boroughs, projection=geoplot.crs.WebMercator(), zoom=12) geoplot.pointplot(final_df[final_df['Asset_Area'] > 10.0 ] , ax=ax) geoplot.polyplot(boroughs, ax=ax, zorder=1) plt.show()
def test_kdeplot(self): try: gplt.kdeplot(series_gaussian_points) gplt.kdeplot(dataframe_gaussian_points) gplt.kdeplot(dataframe_gaussian_points, hue=list_hue_values) gplt.kdeplot(dataframe_gaussian_points, hue=series_hue_values) gplt.kdeplot(dataframe_gaussian_points, hue=map_hue_values) gplt.kdeplot(dataframe_gaussian_points, hue='hue_var') finally: plt.close('all')
print("Joining DataFrames together") signal = pd.concat(signals) signal["date"] = pd.to_datetime(signal.utc_timestamp, unit="ms").map(pd.Timestamp.date) gsignal = gpd.GeoDataFrame(signal, geometry=gpd.points_from_xy(signal.lon, signal.lat)) gsignal.crs = "EPSG:4326" west, south, east, north = (13.05, 52.35, 13.79, 52.65) img, ext = cx.bounds2img(west, south, east, north, ll=True, source=cx.providers.Stamen.TonerLite, zoom=12) img, ext = cx.warp_tiles(img, ext, "EPSG:4326") f, ax = plt.subplots(1, figsize=(9, 9)) plt.imshow(img, extent=ext) gplt.kdeplot(gsignal[gsignal.device_id == 8704], ax=ax, cmap="Reds", shade=True, shade_lowest=False) plt.savefig("users.png", bbox_inches="tight")
# ok but what if we plotted mean counts per hour, over the whole year (for each zip code) #add hour column year_df['hour'] = year_df['firstReportDtm'].apply(lambda x: x.hour) hours_series = pd.Series(range(24)) year_df = year_df.groupby(['ZIP5DIG', 'hour']).agg({'count': 'mean'}) year_df = year_df.unstack().unstack().unstack().reset_index() year_df = year_df.drop(columns=['level_0']).set_index('hour') year_df.plot( ) # plot the mean of a year's worth of police incidents, by hour, for each zip code #############################################33 # Where are incidents most common? Heatmap! ax = gplt.kdeplot(incidents_gdf, clip=zips_df.geometry, shade=True, cmap='Reds', projection=gplt.crs.AlbersEqualArea()) #gplt.webmap(zips_df, ax=ax, projection=gcrs.WebMercator(), zorder=1) gplt.polyplot(zips_df, ax=ax, zorder=1) ############################################ # Which incidents are most common? wordcloud = WordCloud(width=1000, height=800, background_color='black', stopwords=STOPWORDS).generate(' '.join( incidents_gdf['cat_calc'].values)) fig = plt.figure(figsize=(10, 8), facecolor='k', edgecolor='k') plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off')
nyc_boroughs = gpd.read_file(gplt.datasets.get_path('nyc_boroughs')) nyc_collision_factors = gpd.read_file( gplt.datasets.get_path('nyc_collision_factors')) proj = gcrs.AlbersEqualArea(central_latitude=40.7128, central_longitude=-74.0059) fig = plt.figure(figsize=(10, 5)) ax1 = plt.subplot(121, projection=proj) ax2 = plt.subplot(122, projection=proj) gplt.kdeplot(nyc_collision_factors[ nyc_collision_factors['CONTRIBUTING FACTOR VEHICLE 1'] == "Failure to Yield Right-of-Way"], cmap='Reds', projection=proj, shade=True, thresh=0.05, clip=nyc_boroughs.geometry, ax=ax1) gplt.polyplot(nyc_boroughs, zorder=1, ax=ax1) ax1.set_title("Failure to Yield Right-of-Way Crashes, 2016") gplt.kdeplot(nyc_collision_factors[ nyc_collision_factors['CONTRIBUTING FACTOR VEHICLE 1'] == "Lost Consciousness"], cmap='Reds', projection=proj, shade=True, thresh=0.05, clip=nyc_boroughs.geometry,
legend_var='hue', legend_kwargs={ 'bbox_to_anchor': (1, 1), 'frameon': True, 'markeredgecolor': 'k', 'title': "DeathsPer100k" }, extent=covidMap.total_bounds, ax=countyBorders) plt.show() #%% counties = gplt.polyplot(waCounties, edgecolor='silver') gplt.kdeplot(WApoints, shade=False, shade_lowest=False, ax=counties) #%% for republicans counties = gplt.polyplot(waCounties, edgecolor='black', projection=gcrs.Mercator()) #reproject) gplt.kdeplot( WApoints[WApoints.party == 'REPUBLICAN'], #subset shade=True, cmap='Reds', shade_lowest=False, ax=counties, extent=kingMap.total_bounds)
africa = world.query('continent == "Africa"') ax = geoplot.cartogram(africa, scale='pop_est', limits=(0.2, 1), edgecolor='None', figsize=(7, 8)) geoplot.polyplot(africa, edgecolor='gray', ax=ax) ############################################################################### # If we have data in the shape of points in space, we may generate a # three-dimensional heatmap on it using ``kdeplot``. ax = geoplot.kdeplot(collisions, clip=boroughs.geometry, shade=True, cmap='Reds', projection=geoplot.crs.AlbersEqualArea()) geoplot.polyplot(boroughs, ax=ax, zorder=1) ############################################################################### # Alternatively, we may partition the space into neighborhoods automatically, # using Voronoi tessellation. This is a good way of visually verifying whether # or not a certain data column is spatially correlated. ax = geoplot.voronoi(collisions.head(1000), projection=geoplot.crs.AlbersEqualArea(), clip=boroughs.simplify(0.001), hue='NUMBER OF PERSONS INJURED', cmap='Reds', k=None,
# 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:
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, clip=boroughs.geometry) geoplot.polyplot(boroughs, ax=ax) ############################################################################### # Alternatively, we may partition the space into neighborhoods automatically, # using Voronoi tessellation. ax = geoplot.voronoi( injurious_collisions.sample(1000), hue='NUMBER OF PERSONS INJURED', cmap='Reds', scheme='fisher_jenks', clip=boroughs.geometry, linewidth=0) geoplot.polyplot(boroughs, ax=ax) ###############################################################################
def test_hue_params_kdeplot(kwargs): return kdeplot(p_df, **kwargs).get_figure()
""" KDEPlot of Boston AirBnB Locations ================================== This example demonstrates a combined application of ``kdeplot`` and ``pointplot`` to a dataset of AirBnB locations in Boston. The result is outputted to a webmap using the nifty ``mplleaflet`` library. We sample just 1000 points, which captures the overall trend without overwhelming the renderer. `Click here to see this plot as an interactive webmap. <http://bl.ocks.org/ResidentMario/868ac097d671df1ed5ec83eed048560c>`_ """ import geopandas as gpd import geoplot as gplt import geoplot.crs as gcrs import matplotlib.pyplot as plt import mplleaflet boston_airbnb_listings = gpd.read_file( gplt.datasets.get_path('boston_airbnb_listings')) ax = gplt.kdeplot(boston_airbnb_listings, cmap='Greens') gplt.pointplot(boston_airbnb_listings.sample(1000), color='darkgreen', ax=ax) fig = plt.gcf() plt.savefig("boston-airbnb-kde.png", bbox_inches='tight', pad_inches=0.1) # mplleaflet.show(fig)
import geoplot as gplt import geoplot.crs as gcrs import geopandas as gpd ## example code: https://melaniesoek0120.medium.com/data-visualization-how-to-plot-a-map-with-geopandas-in-python-73b10dcd4b4b # use the 'naturalearth_lowers' geopandas datasets world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowers')) # rename the columns world.columns=['continent', 'name', 'CODE', 'geometry'] # merge with your species occurrence data by the same "country code?" or any parameter that is available in both the world and GBIF dataframe df = pd.read_csv(data) merge = pd.merge(world, df, on = 'X') merge.plot(column = '', scheme = '', figsize =(,), legend = True, cmap = '') plt.show() ### kdeplot # link: https://geopandas.org/gallery/plotting_with_geoplot.html # under the kdeplot ax = gplt.polyplot(world, projection=gcrs.AlbersEqualArea()) ax = gplt.kdeplot(df, cmap='Reds', shade=True, shade_lowest=True, clip=world)
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()
collisions = gpd.GeoDataFrame(collisions.head(100000), geometry=collisions.head(100000).apply( pointify, axis='columns')) collisions = collisions[collisions.geometry.map(lambda srs: not (srs.x == 0))] # Plot the data. 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,
def test_clip_params_overlay(kwargs): return kdeplot(p_df, **kwargs).get_figure()
continental_cities = gpd.read_file( geoplot_data.usa_cities()).query('POP_2010 > 100000') contiguous_usa = gpd.read_file(geoplot_data.contiguous_usa()) continental_cities.head() import matplotlib.pyplot as plt collisions = gpd.read_file(geoplot_data.nyc_collision_factors()) boroughs = gpd.read_file(geoplot_data.nyc_boroughs()) census_tracts = gpd.read_file(geoplot_data.ny_census_partial()) percent_white = census_tracts['WHITE'] / census_tracts['POP2000'] obesity = geoplot_data.obesity_by_state() contiguous_usa = gpd.read_file(geoplot_data.contiguous_usa()) contiguous_usa['Obesity Rate'] = contiguous_usa['State'].map( lambda state: obesity.query("State == @state").iloc[0]['Percent']) la_flights = gpd.read_file(geoplot_data.la_flights()) la_flights = la_flights.assign(start=la_flights.geometry.map(lambda mp: mp[0]), end=la_flights.geometry.map(lambda mp: mp[1])) collisions = gpd.read_file(geoplot_data.nyc_collision_factors()) boroughs = gpd.read_file(geoplot_data.nyc_boroughs()) ax = gplt.kdeplot( collisions, projection=gcrs.AlbersEqualArea(), shade=True, # Shade the areas or draw relief lines? shade_lowest=False, # Don't shade near-zeros. clip=boroughs.geometry, # Constrain the heatmap to this area. figsize=(12, 12)) gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(), ax=ax)
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')
f, ax = plt.subplots(1) # Plot polygons in light grey gpd.plotting.plot_polygon_collection(ax, bgm['geometry'], facecolor='grey', alpha=0.25, linewidth=0.1) gpd.plotting.plot_polygon_collection(ax, gdfpol['geometry'], facecolor=None, edgecolor='green', linewidth=0.1) f geoplot.polyplot(f, ax=ax) ax = geoplot.kdeplot(gdfpts_sub, shade=True, shade_lowest=False, cmap="coolwarm", clip=bgm.geometry) geoplot.polyplot(bgm, ax=ax) ax = geoplot.pointplot(gdfpts_sub) geoplot.polyplot(bgm, ax=ax) #optionally write away info df['properties.title'].to_csv('NLD_S2-L2_st31_190626.csv', index=False)