Search code examples
pythongeopandas

How to plot centroid of a Geo panda frame without creating another data frame


New to Geo pandas.

I have a geopanda frame that has county name and geometry.

Trying to plot these counties on a map where area and name of the boundary is annotated at centroid of each county.

I got it working in a very hacky way by creating a Geo panda frame for each information that needs to be plotted, like area or centroid coordinates. Is there a better method of plotting


fig, ax = plt.subplots(figsize=(12, 12))

# Plot counties
counties.plot(ax=ax , color='steelblue', edgecolor='#6a6a6a', linewidth=2 , alpha =0.5 , kind="geo")

# Draw centroids with red circle 

## Method 1: works but need a new gdf created for centroids 
county_centroids.plot(ax=ax , color='red', marker='o', markersize=5 )


## Method 2: NOT WORKING.  Attempt to calculate centroid and plot on the fly  
counties.plot(ax=ax,  color ="red",  marker="o", markersize=6 , x=counties.geometry.x , y =counties.geometry.y , kind = "scatter")

I was wondering if there is some way where one can keep on adding layer over layer like a mosaic and plot it at the end.

Thanks


Solution

  • This demo code shows how to plot several sets of features on the same plot axis (ax1):-

    import geopandas as gpd
    
    # Create a geo-dataframe of countries of the world using cloud data
    # This is the only geo-dataframe that is created
    gpd_lowres = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
    
    # Plot polygons of 7 selected countries
    # The selected countries are NOT retained as a geo-dataframe, 
    #  but the axis `ax1`, which is necessary for use in next plots
    ax1 = gpd_lowres.head(7).plot(figsize=[10,7], color="lightgray")
    
    # Plot buffered-polygons of the centroids
    gpd_lowres.head(7).geometry.representative_point().buffer(distance=8).plot(ax=ax1, color="magenta", alpha=0.35)
    
    # Plot the centroids
    gpd_lowres.head(7).geometry.representative_point().plot(ax=ax1, color="blue",  marker="o", markersize=40 )
    
    # Plot + marks at the centroids and dashed lines connecting the centroids
    ax1.plot(gpd_lowres.head(7).geometry.representative_point().x,
             gpd_lowres.head(7).geometry.representative_point().y, 'r+--') 
    
    # Plot names of the countries
    for (x,y,t) in zip(gpd_lowres.head(7).geometry.representative_point().x.to_list(),
             gpd_lowres.head(7).geometry.representative_point().y.to_list(),
             gpd_lowres.head(7).name.to_list()):
        ax1.text(x, y, '   '+t, fontsize=6, fontweight='ultralight', color="k")
    

    outputplot