I have looked at several related questions, but have not found a working solution beginning with a DataFrame of vertices for multiple polygons. There are existing solutions that address shapefiles where each polygon is contained in a single row.

My issue is the output of gCentroid is clearly weighted toward uneven boundaries. It seems to be generating the mean of the polygon vertices rather than the expected centroid.

library(ggplot2); library(maps); library(sp); library(rgeos)

county_df <- map_data('county')  #mappings of counties by state
county_df <- subset(county_df, region %in% c("illinois", "indiana", 'michigan', 'minnesota', 'wisconsin'))   #subset just for GL
county_df$county <- county_df$subregion
county_df_plot <- county_df

coordinates(county_df) <- c("long", "lat")

# Get centroids
ctrs <- lapply(unique(county_df$group), 
    function(x) gCentroid(SpatialPoints(county_df[county_df$group==x,])))
ctrsout <- setNames( ctrs , unique(county_df$group ) )

# Create data frame 
centroid_df <- do.call(rbind, lapply(ctrsout, data.frame, stringsAsFactors=FALSE))
uniq_logical <- !duplicated(county_df$group)
centroid_df$state <- county_df$region[uniq_logical]
centroid_df$county <- county_df$county[uniq_logical]
names(centroid_df) <- c("longitude", "latitude",'state', 'county')

ggplot(county_df_plot, aes(long, lat)) +  
  geom_polygon(aes(group=group), colour='black', fill=NA) +
  geom_point(data=centroid_df, aes(longitude, latitude), size=1)

1 Answer 1


You seem to be calling gCentroid(SpatialPoints( on something, which is going to convert it to points and find the centroid of the points, not the polygon.

You need to build polygons from your point-based data. Try using map2SpatialPolygons from the maptools package.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.