 # Trouble with showing centroids using plot function

I got a really dumb question to ask, I have trouble with plot() on a map from the spData package and I can't figure it out why. I would appreciate any help or direction.

so I first simplify the original us_states2163 data

# Simplifying the polygon

us_states2163\$AREA = as.numeric(us_states2163\$AREA)
us_states_simp2 = rmapshaper::ms_simplify(us_states2163, keep = 0.01,
keep_shapes = TRUE)

# Creates centroids on the data

plot(us_states_simp2["total_pop_10"], reset = FALSE) so for the us_states_simp2 I can successfully show the centroids on the map, however when I try to use this same st_centroid function on a different dataset it won't show the centroids on the map properly

plot(nz["Population"], reset=FALSE)

This is not dumb, in fact it is rather interesting. For these three approaches should in theory give equivalent results:

``````library(sf)
library(spData)

# dramatis personae: shapes & centroids
data("nz")
cent_nz <- st_centroid(st_geometry(nz))

# base solution
plot(nz["Population"])
plot(cent_nz, pch = 4, col = "red", add = T)
``````

``````# tidyverse solution
library(ggplot2)

ggplot() +
geom_sf(data = nz, aes(fill = Population)) +
geom_sf(data = cent_nz, pch = 4, color = "red")

``````

``````# tmap solution
library(tmap)

tm_shape(nz) + tm_fill(col = "Population") +
tm_shape(cent_nz) + tm_dots(col = "red", shape = 4)
``````

In practice the result is not equivalent - the base plot "steals" the centroids.

I suspect it has something to do with the projection (`st_crs(nz)`) and unless you are absolutely positively required to use base plot I would choose either {ggplot2} or {tmap} for your final vizualization.

Most people do, which is why many edge cases in the base plot scenario are left unresolved.

1 Like

Thank you sir! I just try out the {ggplot2} & {tmap} methods, both work perfectly.

Thanks again for helping.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.