Duccio Piovani
Duccio Piovani

Reputation: 1460

Plot the Geometry of one row of a GeoDataFrame

I would like to plot the geometry contained in a single row of a geopandas dataframe, but I am having problems. Here an example

import geopandas as gpd
import numpy as np
from shapely.geometry import Polygon

p1 = Polygon([(0, 0), (1, 0), (1, 1)])
p2 = Polygon([(2, 0), (3, 0), (3, 1), (2, 1)])
p3 = Polygon([(1, 1), (2, 1), (2, 2), (1, 2)])
index = np.random.random(3)
df = gpd.GeoDataFrame()
df['index'] = index
df['geometry'] = [p1,p2,p3]
df = df.set_geometry('geometry')

Now if I plot using the command df.plot() I get

enter image description here

but if I try to plot only one row, df.loc[:,0].plot()

I get the following error

TypeError: Empty 'DataFrame': no numeric data to plot,

while if if i try

df.loc[:,'geometry'].plot()

I get AttributeError: 'Polygon' object has no attribute 'plot'

What is the correct way of doing this ?

Upvotes: 14

Views: 12349

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210982

Try it this way:

df.loc[[0],'geometry'].plot()
#      ^ ^

Explanation: shapely.geometry.polygon.Polygon doesn't have .plot() method:

In [19]: type(df.loc[0,'geometry'])
Out[19]: shapely.geometry.polygon.Polygon

geopandas.geoseries.GeoSeries does have .plot() method:

In [20]: type(df.loc[[0],'geometry'])
Out[20]: geopandas.geoseries.GeoSeries

Upvotes: 29

Related Questions