Before I start, might I remind you that when you share code, it's best to create a reprex. A reprex consists of the minimal code and data needed to recreate the issue/question you're having. You can find instructions how to build and share one here:
This way we can actually use your code and build on it, because what you shared now can't be run in R.
OK, so to get the centroid, there are a few options:
Calculate using centoid function
library(geophys)
centroid(list(x = c(1,2,1,2), y = c(2,2,5,5)))
[1] 1.5 3.5
Here you provide a list of x and y coordinates, and you get back the centoid
Use sf and ggplot2
This will be a bigger challenge as you have to reformat the data, but the simple features and the ggplot visualisations of them are very powerful. These functions are used to draw complex polygons like maps, and have functions that can position labels built in
Hello,
I clearly cannot include the shape file for the map so I attach the output from the following so it is clear what the issue is. Are you saying sf will wrap the labels?
ggplot() +
geom_polygon(data = ward_map.fort, aes(x = long, y = lat, group = group), fill = "#006633", color = "white") +
theme_void() +
scale_size_continuous(range=c(4,8), breaks = mybreaks) +
geom_text(data = wd_label, aes(x = long, y = lat, label = wd20nm), size = 3)
If you are doing much spatial work in R, I strongly recommend you use the sf package for storing and manipulating spatial objects.
Here, I use the built in NC data set to show how to plot a sf polygons and add text to each polygon using ggplot2::geom_sf_text(). Within that function, I use stringr::str_wrap() in order to force each word in the label to it's own line. Bu default, this will plot the text on the centroid, so you don't need to worry about where to place it.
library(tidyverse)
library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1
nc <- st_read(system.file("shape/nc.shp", package = "sf")) %>%
mutate(NAME = paste(NAME, "County")) %>%
head(10)
#> Reading layer `nc' from data source `C:\R\win-library\4.0\sf\shape\nc.shp' using driver `ESRI Shapefile'
#> Simple feature collection with 100 features and 14 fields
#> geometry type: MULTIPOLYGON
#> dimension: XY
#> bbox: xmin: -84.32385 ymin: 33.88199 xmax: -75.45698 ymax: 36.58965
#> geographic CRS: NAD27
nc %>%
ggplot() +
geom_sf() +
geom_sf_text(aes(label = str_wrap(NAME, 1)), size = 3)
#> Warning in st_point_on_surface.sfc(sf::st_zm(x)): st_point_on_surface may not
#> give correct results for longitude/latitude data