TransWikia.com

Zoom to a plot with GeoPandas based on data from CSV and shapefile

Geographic Information Systems Asked by user3821656 on August 18, 2021

Here is my code:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import descartes
import geopandas as gpd
from sklearn.cluster import KMeans
from sklearn.preprocessing import MinMaxScaler
from sklearn.decomposition import PCA
from shapely.geometry import Point, Polygon
from geopandas import GeoDataFrame as gdf
%matplotlib inline

street_map = gpd.read_file('C:UsersuserDownloadsraccoon_islandraccoon_island.shp')

fig,ax = plt.subplots(figsize = (15, 15)) 
street_map.plot(ax=ax)

enter image description here

df = pd.read_csv('F:AnacondadocsOneDrive_1_9-29-202011.csv')
df = df[['longitude_start','latitude_start']]
crs = {'init': 'epsg:4326'}
df.head() 

enter image description here

geometry = [Point(xy) for xy in zip( df["longitude_start"], df["latitude_start"])]
geometry[:3]

geo_df = gpd.GeoDataFrame(df, crs = crs, geometry = geometry)
geo_df.head()

enter image description here

fig,ax = plt.subplots(figsize = (15, 15))
street_map.plot(ax = ax, alpha = 0.4, color='grey')
geo_df.plot(ax=ax, color='red', markersize=20, marker = '+', label= 'pos')
plt.legend(prop={'size': 15})

enter image description here

I have tried the following but it only seems to make the outer box change size. I would like to zoom in on the result instead.

fig,ax = plt.subplots(figsize = (30, 30))
street_map.plot(ax = ax, alpha = 0.4, color='grey')
geo_df.plot(ax=ax, color='red', markersize=20, marker = '+', label= 'pos')
ax.set_ylim(auto=True)
plt.legend(prop={'size': 15})

ax.set(xlim=(xmin, xmax), ylim=(ymin, ymax))

minx, miny, maxx, maxy = gdf.total_bounds
ax.set_xlim(minx, maxx)
ax.set_ylim(miny, maxy)

One Answer

You are setting limits at three different places. Just pick one.

fig,ax = plt.subplots(figsize = (30, 30))
street_map.plot(ax = ax, alpha = 0.4, color='grey')
geo_df.plot(ax=ax, color='red', markersize=20, marker = '+', label= 'pos')
plt.legend(prop={'size': 15})

minx, miny, maxx, maxy = gdf.total_bounds
ax.set_xlim(minx, maxx)
ax.set_ylim(miny, maxy)

Here is a reproducible example:

import geopandas as gpd

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
africa = world[world.continent == 'Africa']
cities = gpd.read_file(gpd.datasets.get_path('naturalearth_cities'))

ax = africa.plot()
cities.plot(ax=ax, color='r')

minx, miny, maxx, maxy = africa.total_bounds
ax.set_xlim(minx, maxx)
ax.set_ylim(miny, maxy)

result

Correct answer by martinfleis on August 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP