2

I'm coloring countries based on variable v1 and I want to add geom_point to each of those countries and set geom size equal to my variable v2. However, when I add the geom_point, the geom_point for the USA does not appear and other points are scattered on the map. Below is my script, as per other posts I've seen here.

ddf <- structure(list(Country = c("Brazil", "United States", "Sweden", "South Korea", "Senegal", "Pakistan", "Norway","New Zealand", "Mexico","India", 
                                  "Netherlands", "Denmark", "Czech Republic", "China"), 
                      v1 = c(2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 9L, 1L, 3L, 1L, 4L), v2 = c(13, 3, 2, 2, 2, 11, 4, 15, 4, 4, 3, 12, 5, 20)), 
                 .Names = c("Country", "v1", "v2"), row.names = c(2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 9L, 1L, 3L, 1L, 4L), class = "data.frame", 
                 na.action = structure(2L, .Names = "2", class = "omit"))


data(wrld_simpl)
wrld_simpl@data$id <- wrld_simpl@data$NAME
wrld <- fortify(wrld_simpl, region="id")
wrld <- subset(wrld, id != "Antarctica") 

SelectedCountries = subset(wrld, id %in% c("Brazil", "United States", "Sweden", "South Korea", "Senegal", "Pakistan", "Norway", 
           "New Zealand", "Mexico", "India", 
           "Netherlands", "Denmark", "Czech Republic", "China"))

CountryCenters <- aggregate(cbind(long, lat) ~ id, data = SelectedCountries, 
                            FUN = function(x) mean(range(x)))

ddf = merge(ddf, CountryCenters, by.x = "Country", by.y = "id")

gg <- ggplot() +
  geom_map(data=wrld, map=wrld, aes(map_id=id, x=long, y=lat), fill="grey90", size=0.25) +
  geom_map(data=ddf, map=wrld, aes(map_id=Country, fill = v1), size=0.25) +
  geom_point(data=ddf, aes(x=long, y=lat, size = v2), colour = "red")
  
gg

Any help would be appreciated!

1 Answers1

0

It appears your centroid calculation has an issue with United States and New Zealand. One solution is to use sf for your geoprocessing and geom_sf for your plotting, like this:

library(maptools)
library(ggplot2)
library(sf)

data(wrld_simpl)
world <- st_as_sf(wrld_simpl)

# Define polygon features
poly_ddf <- st_as_sf(merge(ddf, world, by.x = "Country", by.y = "NAME"))

# Calculate centroids
# Centroid calc prefers projected data
# PICK A PROJECTION THAT MATCHES THE GOALS OF YOUR WORK
ddf_p <- st_transform(poly_ddf, crs = 6933)
centroids <- st_centroid(ddf_p)
#> Warning in st_centroid.sf(ddf_p): st_centroid assumes attributes are constant
#> over geometries of x

ggplot() +
  geom_sf(data = world) +
  geom_sf(data = poly_ddf, aes(fill = v1)) +
  geom_sf(data = centroids, aes(size = v2), color = "red")

enter image description here

Skaqqs
  • 4,010
  • 1
  • 7
  • 21