【问题标题】:.savefig with geopandas results in empty figure.savefig 与 geopandas 导致空图
【发布时间】:2021-07-02 13:31:56
【问题描述】:

我想通过导入瑞士的 shapefile (https://www.swisstopo.admin.ch/de/geodata/landscape/boundaries3d.html) 并放大感兴趣的区域来生成苏黎世州的图。在最后一步中,我想将生成的图像保存为 .eps 文件。问题是保存的图片文件是空的。

首先导入 geopandas 和 matplotlib 包

import geopandas
import matplotlib.pyplot as plt

然后加载shapefile的数据

gdf = geopandas.read_file("swissBOUNDARIES3D_1_3_TLM_KANTONSGEBIET.shp")

然后绘制瑞士地图。苏黎世州的颜色与所有其他州不同。在此之后,对苏黎世州进行了缩放。

fig = plt.figure(figsize=(30, 18))
ax2 = gdf.plot(figsize=(30,18), edgecolor='black')
gdf[gdf.NAME == "Zürich"].plot(edgecolor='black', color='lightskyblue', ax=ax2)
gdf[gdf.NAME != "Zürich"].plot(edgecolor='black', color='aliceblue', ax=ax2)
plt.xlim(650000,750000)
plt.ylim(220000,290000)

然后应该保存生成的图像。


fig.savefig("filename2.eps", format='eps')
plt.show()

但是生成的图片是空的。格式改为png时也是空的。

【问题讨论】:

    标签: matplotlib geopandas savefig


    【解决方案1】:

    生成的图像是空的,因为您的绘图不在正确的图形上。 gdf.plot() 创建一个新图形。为了保存该图形,您可以删除对plt.figure() 的调用并从轴中获取图形:

    ax2.figure.savefig("filename2.eps", format='eps')
    

    或创建一个子图并将创建的轴作为参数传递给第一个gdf.plot()

    fig, ax2 = plt.subplots(figsize=(30,18))
    gdf.plot(edgecolor='black', ax=ax2)
    gdf[gdf.NAME == "Zürich"].plot(edgecolor='black', color='lightskyblue', ax=ax2)
    gdf[gdf.NAME != "Zürich"].plot(edgecolor='black', color='aliceblue', ax=ax2)
    plt.xlim(650000,750000)
    plt.ylim(220000,290000)
    fig.savefig("filename2.eps", format='eps')
    

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 2022-11-12
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多