Reputation: 1237
When using fig,ax from matplotlib in combination with a geopandas dataframe AND when changing the .crs, the plot is empty. Anyone an idea why this happens and how to fix it?
Dataset: https://hub.arcgis.com/datasets/esribeluxdata::belgium-municipalities-1
import geopandas as gpd
import matplotlib.pyplot as plt
from fiona.crs import from_epsg
belgium = gpd.read_file("BELGIUM__Municipalities.shp")
fig,ax = plt.subplots()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
municipalities.plot(ax = ax) -> crs=WGS84 (lat/long)
plt.show()
municipalities = municipaliteis.to_crs("epsg:3395") -> crs to Mercator projection
municipalities.crs
municipalities.plot(ax = ax) -> plot = empty: Why does this happen, how to fix it?
plt.show()
municipalities.plot() -> plot = Mercator plot
plt.show()
Upvotes: 2
Views: 902
Reputation: 1501
It is OK to change crs, below I made it with subplots. If you keep same ax
object I think it could be difficult to see them both cause limits are not at all the same.
import geopandas as gpd
import matplotlib.pyplot as plt
from fiona.crs import from_epsg
municipalities = gpd.read_file("BELGIUM__Municipalities.shp")
fig, ax = plt.subplots(1, 2)
for a in ax:
a.spines['top'].set_visible(False)
a.spines['right'].set_visible(False)
a.spines['left'].set_visible(False)
a.spines['bottom'].set_visible(False)
a.get_xaxis().set_visible(False)
a.get_yaxis().set_visible(False)
municipalities.plot(ax=ax[0], color='red')
municipalities = municipalities.to_crs("epsg:3395")
municipalities.plot(ax=ax[1])
plt.show()
EDIT: In your second call, your ax is no more referring to an visually existing area so, you can do that to recreate it:
import geopandas as gpd
import matplotlib.pyplot as plt
from fiona.crs import from_epsg
municipalities = gpd.read_file("BELGIUM__Municipalities.shp")
def init():
fig,ax = plt.subplots()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
return ax
ax = init()
municipalities.plot(ax = ax)
plt.show()
ax = init()
municipalities = municipalities.to_crs("epsg:3395")
municipalities.plot(ax=ax)
plt.show()
municipalities.plot()
plt.show()
In the last call, matplotlib
creates a new axes object as you do not mention any axes to work with.
Upvotes: 2