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
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 ?
A GeoDataFrame may also contain other columns with geometrical (shapely) objects, but only one column can be the active geometry at a time.
A GeoDataFrame object is a pandas. DataFrame that has a column with geometry. In addition to the standard DataFrame constructor arguments, GeoDataFrame also accepts the following keyword arguments: Parameters. crsvalue (optional)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With