change NA-color in zipcode map

Viewed 341

I created a map on German zip code with my data. My data did not contain every zip code, so I do have missing values. Missing values are drawn black in the map; I want them to be white. How can I change it?

ger_plz <- readOGR(dsn = ".", layer = "plz-2stellig")

gpclibPermit()
#convert the raw data to a data.frame as ggplot works on data.frames
ger_plz@data$id <- rownames(ger_plz@data)
ger_plz.point <- fortify(ger_plz, region="id")
ger_plz.df <- inner_join(ger_plz.point,ger_plz@data, by="id")

head(ger_plz.df)
ggplot(ger_plz.df, aes(long, lat, group=group )) + geom_polygon()

#data file
Ers <- table(data.plz$plz)
df<- as.data.frame(Ers)

# variable name 'region' is needed for choroplethr
ger_plz.df$region <- ger_plz.df$plz
head(ger_plz.df)

#subclass choroplethr to make a class for your my need
GERPLZChoropleth <- R6Class("GERPLZChoropleth",
                            inherit = choroplethr:::Choropleth,
                            public = list(
                              initialize = function(user.df) {
                                super$initialize(ger_plz.df, user.df)
                              }
                            )
)
#choropleth needs these two columnames - 'region' and 'value'
colnames(df) = c("region", "value")

#instantiate new class with data
c <- GERPLZChoropleth$new(df)

#plot the data
c$ggplot_polygon = geom_polygon(aes(fill = value), color = NA)
c$title = "Erstsemester Landau 2017"
c$legend= "Heimatort"
c$set_num_colors(9)
c$render()

picture of my map

2 Answers

I have kind of a solution for you, but it's not the best. You need to plot the map, and after that you can change the colour. Choose another color palette to get the NA Data white. I tryed it with palette = "OrRd" and it works fine.

c$ggplot_polygon = geom_polygon(aes(fill = value), color = NA)
c$title = "Erstsemester Landau 2017"
c$legend= "Heimatort"
c$set_num_colors(9)
choro <- c$render()
choro
choro+scale_fill_brewer(palette = "OrRd")

You can then use the palette parameter also with other colors:

Diverging: BrBG, PiYG, PRGn, PuOr, RdBu, RdGy, RdYlBu, RdYlGn, Spectral

Qualitative Accent: Dark2, Paired, Pastel1, Pastel2, Set1, Set2, Set3

Sequential: Blues, BuGn, BuPu, GnBu, Greens, Greys, Oranges, OrRd, PuBu, PuBuGn, PuRd, Purples, RdPu, Reds, YlGn, YlGnBu, YlOrBr, YlOrRd

(Source: https://www.rdocumentation.org/packages/ggplot2/versions/3.3.2/topics/scale_colour_brewer)

Since R tells you what zip codes are missing, I did the following to set my NA values to 0 thus making them white (even when using the blue palette).

missingZips <- data.frame("region" = c(LIST ZIP CODES--i.e. 12345, 34556))
missingZips$value=0
merged_df <- rbind(df, missingZips)
Related