Digital representation
Object View
Field View
# Import necessary geometric objects from shapely module
from shapely.geometry import Point, LineString, Polygon
from descartes.patch import PolygonPatch
import matplotlib.pyplot as plt
# create points
lu = Point(34.417336, -119.869598)
ru = Point(34.417336, -119.853698)
lb = Point(34.409077, -119.869598)
rb = Point(34.409077, -119.853698)
def plot_coords(ax, ob):
x, y = ob.xy
ax.plot(x, y, 'o', color='#999999', zorder=1)
fig, ax = plt.subplots()
plot_coords(ax, lu)
plot_coords(ax, ru)
plot_coords(ax, lb)
plot_coords(ax, rb)
def plot_line(ax, ob):
x, y = ob.xy
ax.plot(x, y, color='red', alpha=0.7, linewidth=3, solid_capstyle='round', zorder=2)
# create a line from points
fig, ax = plt.subplots()
line = LineString([lu,rb,ru,lb, lu])
plot_line(ax, line)
# length of a line in degrees
print(line.length)
print(line.geom_type)
0.052352122341691086 LineString
poly = Polygon([lu,ru,rb,lb,lu])
print('area:', poly.area)
print('bbox:', poly.bounds)
poly
area: 0.00013131809999994282 bbox: (34.409077, -119.869598, 34.417336, -119.853698)
import geopandas as gpd
import numpy as np
# reading data
gdf = gpd.read_file('https://raw.githubusercontent.com/codeforgermany/click_that_hood/main/public/data/california-counties.geojson')
print(gdf.shape)
gdf.head()
(58, 5)
name | cartodb_id | created_at | updated_at | geometry | |
---|---|---|---|---|---|
0 | Alameda | 1 | 2015-07-04 21:04:58+00:00 | 2015-07-04 21:04:58+00:00 | MULTIPOLYGON (((-122.31293 37.89733, -122.2884... |
1 | Alpine | 2 | 2015-07-04 21:04:58+00:00 | 2015-07-04 21:04:58+00:00 | POLYGON ((-120.07239 38.70277, -119.96495 38.7... |
2 | Amador | 3 | 2015-07-04 21:04:58+00:00 | 2015-07-04 21:04:58+00:00 | POLYGON ((-121.02726 38.48925, -121.02741 38.5... |
3 | Butte | 4 | 2015-07-04 21:04:58+00:00 | 2015-07-04 21:04:58+00:00 | POLYGON ((-121.87925 39.30361, -121.90831 39.3... |
4 | Calaveras | 5 | 2015-07-04 21:04:58+00:00 | 2015-07-04 21:04:58+00:00 | POLYGON ((-120.87605 38.02889, -120.91875 38.0... |
# keep only two columns
gdf = gdf[['name', 'geometry']]
print(gdf.shape)
(58, 2)
# let's randomly generate a variable to practice plotting
gdf['butter_per_capita'] = np.random.randint(1, 50, gdf.shape[0])
# histogram
gdf.butter_per_capita.plot(kind='hist')
<AxesSubplot: ylabel='Frequency'>
# check projection
gdf.crs
<Geographic 2D CRS: EPSG:4326> Name: WGS 84 Axis Info [ellipsoidal]: - Lat[north]: Geodetic latitude (degree) - Lon[east]: Geodetic longitude (degree) Area of Use: - name: World. - bounds: (-180.0, -90.0, 180.0, 90.0) Datum: World Geodetic System 1984 ensemble - Ellipsoid: WGS 84 - Prime Meridian: Greenwich
gdf.plot()
<AxesSubplot: >
# some modifications
gdf.plot(fc='gray', ec='white', linewidth=.5)
<AxesSubplot: >
# choropleth mapping
gdf.plot(column='butter_per_capita', legend=True,
legend_kwds={'label': 'Butter Consumption in CA'});
# choropleth mapping
gdf.plot(column='butter_per_capita', legend=True,
cmap='OrRd',
legend_kwds={'label': 'Butter Consumption in CA'});
# layer for better visuals
fig, ax = plt.subplots(figsize=(5,5))
gdf.plot(column='butter_per_capita', legend=True,
cmap='OrRd',
legend_kwds={'label': 'Butter Consumption in CA'},ax=ax)
gdf.plot(ax=ax, fc='None', ec='k') # adds county boundaries
_ = ax.axis("off") # remove axes
fig.savefig('butter.png', dpi=150) # save file
# plot centroids of counties
fig, ax = plt.subplots(figsize=(5,5))
gdf.plot(ax=ax, fc='None', ec='k'); # adds county boundaries
gdf.centroid.plot(ax=ax, marker='*', color='red');
ax.set_title('California Counties and Centroids', fontsize=16)
C:\Users\barguzin\AppData\Local\Temp\ipykernel_29120\1412698061.py:5: UserWarning: Geometry is in a geographic CRS. Results from 'centroid' are likely incorrect. Use 'GeoSeries.to_crs()' to re-project geometries to a projected CRS before this operation. gdf.centroid.plot(ax=ax, marker='*', color='red');
Text(0.5, 1.0, 'California Counties and Centroids')
import matplotlib.patches as mpatches
# plot specific areas
socal_counties = ['Imperial', 'Kern', 'Los Angeles', 'Orange', 'Riverside', 'San Bernardino', 'San Diego', 'San Luis Obispo', 'Santa Barbara', 'Ventura']
socal = gdf.loc[gdf.name.isin(socal_counties),]
fig, ax = plt.subplots()
gdf.plot(ax=ax, fc='None', ec='k'); # adds county boundaries
socal.plot(ax=ax, fc='red', ec='r', lw=0, alpha=.5); # plot socal
socal.dissolve().plot(ax=ax, fc='None', ec='r', lw=2) # demo dissolve
# add legend
red_patch = mpatches.Patch(color='red', label='SoCal', alpha=.5)
ax.legend(handles=[red_patch])
<matplotlib.legend.Legend at 0x1e58ba038b0>