0

I'm new to geoplotting and I want to use sf to plot a map of Germany on the state level, with state values colored by a variable in a separate data set. How do I best go about this?

I have loaded the data and the sf object like this:

library(sf)
library(tidyverse)
theme_set(theme_bw())
library(rnaturalearth)
library(rnaturalearthdata)

dat <- read.table(text="
      state value
      Sachsen 10
      Bayern 30
      Rheinland-Pfalz 50
      Saarland 70
      Schleswig-Holstein 90
      Niedersachsen  100
      Nordrhein-Westfalen 80
      Baden-Württemberg 60
      Brandenburg 40
      Mecklenburg-Vorpommern 20
      Bremen 40
      Hamburg 60
      Hessen 15
      Berlin 10
      Thüringen 80
      Sachsen-Anhalt 20
", header=T)

ger_fedstates <- ne_states(country = "germany")

sp::plot(ne_states(country = "germany"))

How do I now color each state by the value in dat$value? I'm at a loss of how to best combine these two.

Ivo
  • 3,890
  • 5
  • 22
  • 53

1 Answers1

1

As you loaded the tidyverse and sf you can just use left_join(). You can use as well data from giscoR, that provides the names of the states in Deustch (giscoR source is GISCO, the Eurostat agency for spatial data), so the names can match seamlessly. Then again, use ggplot2 (or tmap, mapsf or base plot) to create your plot. Key advice here is to use sf package instead of sp, since sp is superseeded by sf:

library(sf)
#> Linking to GEOS 3.8.0, GDAL 3.0.4, PROJ 6.3.1; sf_use_s2() is TRUE
library(tidyverse)
theme_set(theme_bw())
library(giscoR)

ger_fedtstates <- gisco_get_nuts(
  nuts_level = 1,
  resolution = 10,
  country = "Germany",
  year = 2021
)



dat <- read.table(text = "
      state value
      Sachsen 10
      Bayern 30
      Rheinland-Pfalz 50
      Saarland 70
      Schleswig-Holstein 90
      Niedersachsen  100
      Nordrhein-Westfalen 80
      Baden-Württemberg 60
      Brandenburg 40
      Mecklenburg-Vorpommern 20
      Bremen 40
      Hamburg 60
      Hessen 15
      Berlin 10
      Thüringen 80
      Sachsen-Anhalt 20
", header = T)

ger_fedstates_end <- ger_fedtstates %>%
  left_join(dat, by = c("NUTS_NAME" = "state"))


# With base
plot(ger_fedstates_end["value"])



# With ggplot2
ggplot(ger_fedstates_end) +
  geom_sf(aes(fill = value))



# With tmap
library(tmap)

tm_shape(ger_fedstates_end) +
  tm_polygons(col = "value")



# With mapsf
library(mapsf)

mf_choro(ger_fedstates_end, var = "value")

Created on 2023-02-21 with reprex v2.0.2

dieghernan
  • 2,690
  • 8
  • 16