As the title says, when I plot some geopandas data by itself the plot limits are exactly as I specify them, but when I add the basemap through contextily (v1.1.0) the extent of the tiles determines the size of the underlying image, and the plot limits become the extend of the image. As a result, the region I actually want to plot is smaller and often off-center (which is bad).
Other people have posted that they fixed similar problems with the extent by using the xlim and ylim parameters, but this is not working for me.
xMin, yMin, xMax, yMax = list(theData['geometry'].total_bounds)
##-- add a buffer around the data area.
xMin = xMin - (0.03 * (xMax - xMin))
xMax = xMax + (0.03 * (xMax - xMin))
yMin = yMin - (0.03 * (yMax - yMin))
yMax = yMax + (0.03 * (yMax - yMin))
ax = theData.plot(ax=ax, column=theVariable)
ax.set_xlim(xMin, xMax)
ax.set_ylim(yMin, yMax)
basemap,extent = ctx.bounds2img(xMin, yMin, xMax, yMax, zoom=12, source=tileSource)
ax.imshow(basemap, extent=extent)
ax.set_xlim(xMin, xMax)
ax.set_ylim(yMin, yMax)
plt.show()
In my particular case, the value of xMin is 15,535,161, but the plot extends westward past 15,530,000 (smaller than xMin).
The contextily documentation says that the option reset_extent
has [Default=True]
and If True, the extent of the basemap added is reset to the original extent (xlim, ylim) of ax
. However, this seems to be a lie because it's not happening.
You can see in my code snippet that I explicitly set the lims before AND after the plotting and basemap, and this also has no effect. I expect it crop the visible part of plot to within the plot range (as in other languages I've used for plotting maps).
So, either this is broken in contextily, it's not actually supposed to do the (obviously desired) cropping I'm looking for, or I am doing something wrong that I can't find or figure out. Hopefully somebody can spot the problem and tell me how to get these map plots to look how they are supposed to.
Note that when I change the imshow command to ax.imshow(basemap, extent=[xMin, xMax, yMin, yMax])
my data appears correctly in the plot limits, but the basemap doesn't change and they are not aligned.
Note also that if I remove the padding, my data goes right up to the edge on the North, South, and East side, but the map extends to the same (wrong) place on the West boundary.