Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zooming and saving only a central part of interest in a matplotlib geopandas figure

I plot a map using geopandas and colormap with the code:

import numpy as np

## make up some random data
df = pd.DataFrame(np.random.rand(20, 3), columns=['x', 'y', 'val'])
df['geometry'] = df.apply(lambda row: shapely.geometry.Point(row.x, row.y), axis=1)

# make it a geopandas DataFrame
gdf = gpd.GeoDataFrame(df)

## the plotting
ax = gdf.plot(column='val', colormap='hot', vmin=vmin, vmax=vmax)

# add colorbar
fig = ax.get_figure()
cax = fig.add_axes([0.9, 0.1, 0.03, 0.8])
sm = plt.cm.ScalarMappable(cmap='hot', norm=plt.Normalize(vmin=0, vmax=1))
# fake up the array of the scalar mappable. Urgh...
sm._A = []
fig.colorbar(sm, cax=cax)

Then, I get this figure (the data is different from the example above)

Final map of agent-based model with Taxes paid by individual firms

As you can see, the firms of interest are in the center of the map.

I would like to provide a coordinates envelope, rezoom the image, keeping the colorbar and savefig()

like image 947
B Furtado Avatar asked Sep 28 '17 19:09

B Furtado


1 Answers

I think you're looking for the gdf.total_bounds attribute

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

I think this should provide the zoom level you're looking for. You can also add a 'pad' to each of these to ensure your points are not right at each of the axes boundaries.

like image 81
aorr Avatar answered Oct 24 '22 18:10

aorr