13

I have installed the following two packages:

library(ggmap)
library(maps)

I have found code online to create a world map (see below). How do I zoom the plot on a country level? For example, Denmark.

ggplot()+
  borders("world", colour="gray50", fill="gray50")

Enter image description here

17

If we look at ?borders and, for more into, ?map, we see that we may use the regions argument:

ggplot() + borders(regions = "Denmark", colour = "gray50", fill = "gray50") 

enter image description here

  • 1
    Also, a very beautiful package for maps is leaflet: i.e l <- leaflet() %>% setView(lat = 50.85045, lng = 4.34878, zoom=5) %>% addTiles(group="OSM") – JonnyCrunch Jan 29 at 12:35
  • @Julius Vainora: Thanks. Can I add layers to this plot? For example if I find a data set with "state boundries"? – David Jan 29 at 12:40
  • 2
    @David, yes, layers can be added, for instance + geom_point(data = data.frame(x = 12, y = 56), aes(x = x, y = y)) adds a point. – Julius Vainora Jan 29 at 12:42
  • 1
    When using maps, you might want to add coord_cartesian(), so that the scale of the x and the y axes match. – JAD Jan 29 at 21:44
9

Get the bounds of Denmark in lat-long and use coord_fixed:

ggplot() + borders("world", colour="gray50", fill="gray50") + coord_fixed(xlim=c(7, 12), ylim=c(52, 58))

Enter image description here

You can get the bounds from the map package:

> map("world", "Denmark", plot=FALSE)$range
[1]  8.121484 15.137110 54.628857 57.736916

And you might want to expand these a bit for nicer spacing and more context.

  • @ when I run map("world","Denmark",plot=FALSE)$range I get NULL? – David Jan 29 at 12:42
  • Odd. Does map("world","Denmark") produce a map of Denmark? What about "France" or "Belgium"? Is it using local country names ("Danmark")? Does map("world") draw a map? Does map("world",plot=FALSE)$names return a vector of country/region names? If those don't work, then that's very odd and you should ask a new Q or report a bug... – Spacedman Jan 29 at 12:59
  • @ Spacedan: None of them work either NULL or error. But I can create the plots in the answers... – David Jan 29 at 13:04
  • 1
    Start a new clean R session, do library(maps), then try? Maybe you've got something masking the maps::map function. Probably purrr::map? Don't use library(tidyverse). – Spacedman Jan 29 at 13:05
  • 4
    @ Spacedman: I think it is okay if I use maps::map. Maybe it thought the map function from the purrr package... – David Jan 29 at 13:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.