0
votes

I was trying to create a choropleth map using ggplot2 and a public shape-file of Switzerland (it is included in this zip-file: PLZO_PLZ.shp)

library(rgdal)    
library(ggplot2)   
library(ggmap)   
library(broom)

# Load Shapefile
shapefile <- readOGR(file.choose())

# Next the shapefile has to be converted to a dataframe for use in ggplot2
shapefile_df <- fortify(shapefile)

ggplot(data = shapefile_df) +
  geom_path(aes(x = long, y = lat, group = group),  color="black") +
  theme_void() 

The result looks like this:

enter image description here

However, I don't want to plot the map only, I also want to color the different municipalities according to certain attributes. Each municipality has a four-digit zip code (called "PLZ"). These values can be seen in shapefile$PLZ.

But how can I assign attributes to certain municipalities? An example:

fakeData <- data.frame(PLZ = c(8001, 8002, 8048), values = c(20, 40, 99))

I would like to colour the municipalities 8001, 8002 and 8048. But how can I join the variable values into shapefile or shapefile_df? So that I can plot it like this:

ggplot(data = shapefile_df) +
  geom_path(aes(x = long, y = lat, group = group, fill = values),  color="black") +
  theme_void() 

If I try "left_join" on shapefile the error message is that the method is not applicable to an object of the class "c('SpatialPolygonsDataFrame', 'SpatialPolygons', 'Spatial')". In shapefile_df however, there is no variable PLZ any more. I have also tried

shapefile@data$id <- rownames(shapefile@data)
shapefile_df <- fortify(shapefile, region = "PLZ")

which leads to the following error: Error in maptools::unionSpatialPolygons(cp, attr[, region]) : isTRUE(gpclibPermitStatus()) is not TRUE

1

1 Answers

1
votes

I would recommend using the sf package to read the shapefile. Then you can do the left_join without any problems. Finally, you can do the plot using geom_sf and change the fill default values for NA from gray to transparent using scale_fill_distiller (you can also choose the fill palette for non-NA values).

library(sf)

# Read shapefile as sf
shapefile_df <- st_read(file.choose())

# Left_join by PLZ
shapefile_df <- shapefile_df %>%
  left_join(fakeData, by = "PLZ")

# Do plot
ggplot(shapefile_df, 
       aes(fill = values)) + 
  # Plot sf 
  geom_sf(show.legend = F) +
  # Indicate fill palette and set NA values to transparent
  scale_fill_distiller(type = "seq",
                       palette = "Blues",
                       na.value = "transparent") +
  # Add void theme
  theme_void()