简体   繁体   中英

ggplot + maptools + ggmap: color gradient?

I have the following data frame:

pacman::p_load(maptools, ggplot2, raster, ggmap)

df <- tribble( ~ country,   ~ maternity_leave,
               "Argentina",               390,
               "Bahamas",                 390,
               "Barbados",                360,
               "Belize",                  420,
               "Bolivia",                 390,
               "Brazil",                  510,
               "Chile",                   540,
               "Colombia",                540,
               "Costa Rica",              510,
               "Dominican Republic",      420,
               "Ecuador",                 360,
               "El Salvador",             480,
               "Guatemala",               360,
               "Guyana",                  390,
               "Haiti",                   360,
               "Honduras",                240,
               "Jamaica",                 240,
               "Mexico",                  360,
               "Nicaragua",               360,
               "Panama",                  420,
               "Paraguay",                540,
               "Peru",                    420,
               "Suriname",                480,
               "Trinidad and Tobago",     420,
               "Venezuela",               780)

countries <- maternity_leave %>% 
  pull(country)
  
map <- borders("world", regions = countries, fill = "grey70", colour = "black")

ggplot() + 
  map +
  xlab("Longitude (decimals)") + 
  ylab("Latitude (decimals)") + 
  theme(panel.border = element_blank(), 
        panel.grid.major = element_line(colour = "grey80"), 
        panel.grid.minor = element_blank())

But I want to use the variable maternity_leave as a base for color gradient and I do not know how. I tried by changing the map function and scale_colour_gradient2 and sacale_fill_gradient2 with no success.

I would appreciate any help!

I'm using tmap to get the world data. For me it works faster and more clearly.

I join your df data.frame together with the World info available in tmap to only have the countries that are in your data.frame, but with the maternity_leave column added. This column you can then use as the fill in geom_sf. The scale_fill_ functions are not really needed unless you want to specify a different color scheme.

library(ggplot2)
library(tmap)
library(dplyr)

data("World")
map_data <- World %>% 
  inner_join(df, by = c("name" = "country"))

ggplot(map_data) + 
  geom_sf(aes(fill = maternity_leave)) + 
  scale_fill_gradient2() # not really needed but gives different colors.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM