I\'m attempting to use ggplot2 and maps to plot the names of the counties in NY state. My approach was to find the means of latitude and longitude by county (I assume this
I know this is an old question that's been answered, but I wanted to add this in case anyone looks here for future help.
The maps package has the map.text
function, which uses polygon centroids to place labels. Looking at its code, one can see that it uses the apply.polygon
and centroid.polygon
functions to find the centroids. These functions aren't visible when the package is loaded, but can still be accessed:
library(ggplot2); library(maps)
county_df <- map_data('county') #mappings of counties by state
ny <- subset(county_df, region=="new york") #subset just for NYS
ny$county <- ny$subregion
cnames <- aggregate(cbind(long, lat) ~ subregion, data=ny, FUN=mean)
# Use the map function to get the polygon data, then find the centroids
county_poly <- map("county", "new york", plot=FALSE, fill = TRUE)
county_centroids <- maps:::apply.polygon(county_poly, maps:::centroid.polygon)
# Create a data frame for graphing out of the centroids of each polygon
# with a non-missing name, since these are the major county polygons.
county_centroids <- county_centroids[!is.na(names(county_centroids))]
centroid_array <- Reduce(rbind, county_centroids)
dimnames(centroid_array) <- list(gsub("[^,]*,", "", names(county_centroids)),
c("long", "lat"))
label_df <- as.data.frame(centroid_array)
label_df$county <- rownames(label_df)
p <- ggplot(ny, aes(long, lat, group=group)) + geom_polygon(colour='black', fill=NA)
plabels <- geom_text(data=label_df, aes(label=county, group=county))
p + plabels