微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Geopandas 通过在绘图时指定列来绘图

如何解决Geopandas 通过在绘图时指定列来绘图

我正在将来自 here 的 geojson 数据读入名为 gdf 的 GeoDataFrame。

我还使用 gdf['centroid'] = gdf.centroid 计算了每个多边形的质心。

通过使用 gdf.set_geometry("<centroid | geometry>") 将列设置为几何列,我可以单独绘制质心或多边形。因此,以下代码有效:

gdf.plot()    #By default the geometry column is the column to plot
gdf = gdf.set_geometry("centroid")
gdf.plot()

但是,当我尝试运行以下代码时:

gdf['geometry'].plot() #Geometry column has been set as centroid before

或者,

gdf = gdf.set_geometry("geometry")
gdf["centroid"].plot()

我收到以下错误

TypeError                                 Traceback (most recent call last)
<ipython-input-22-0330c435e2c9> in <module>
      1 gdf = gdf.set_geometry("centroid")
----> 2 ax = gdf['geometry'].plot()
      3 #gdf["centroid"].plot(ax=ax,color="black")

C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\pandas\plotting\_core.py in __call__(self,*args,**kwargs)
    953                     data.columns = label_name
    954 
--> 955         return plot_backend.plot(data,kind=kind,**kwargs)
    956 
    957     __call__.__doc__ = __doc__

C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\pandas\plotting\_matplotlib\__init__.py in plot(data,kind,**kwargs)
     59             kwargs["ax"] = getattr(ax,"left_ax",ax)
     60     plot_obj = PLOT_CLASSES[kind](data,**kwargs)
---> 61     plot_obj.generate()
     62     plot_obj.draw()
     63     return plot_obj.result

C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\pandas\plotting\_matplotlib\core.py in generate(self)
    276     def generate(self):
    277         self._args_adjust()
--> 278         self._compute_plot_data()
    279         self._setup_subplots()
    280         self._make_plot()

C:\Program Files\ArcGIS\Pro\bin\Python\envs\arcgispro-py3\lib\site-packages\pandas\plotting\_matplotlib\core.py in _compute_plot_data(self)
    439         # no non-numeric frames or series allowed
    440         if is_empty:
--> 441             raise TypeError("no numeric data to plot")
    442 
    443         self.data = numeric_data.apply(self._convert_to_ndarray)

TypeError: no numeric data to plot

即使我可以将列设置为几何图形然后进行绘图,但需要在绘图时通过指定特定列进行绘图以覆盖多个几何图形。

--完整代码--

import geopandas
import geoplot

gdf = geopandas.read_file("<path to file>.geojson")
print(gdf.head())
print(gdf.crs)
gdf.plot(legend=True)

gdf['centroid'] = gdf.centroid
gdf = gdf.set_geometry("centroid")
gdf.plot() #Works
gdf['centroid'].plot() #Works
gdf['geometry'].plot() #Error is thrown here
type(gdf)

解决方法

你能在没有 import geoplot 行的情况下尝试吗?对我来说似乎工作正常。enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。