2
votes

My problem is, that I have a sf-object, which I want to map with ggplot and fill the counties with the colour of a factor variable. I defined for each factor level a color which should be fixed even if subsetting the dataframe.

My problem is: I see in the legend my factor with the correct colours, I see my map, but the counties are not filled with any colour.

My test dataset is here: https://wolke.netzbegruenung.de/s/wPfNEPrSkcsLaHX

First step:

I define an Indicator variable, which live between 0 and any positive value. Values above 1 are arlaming. Normal are values below 0.3. To get a forcast, what will happen in the future I will map my counties in the colour of the categorised Indexvariable. Therefor I define a data.frame with the colors:

brk <- c(0,0.1,0.5,0.6,0.8,0.9,1,Inf)
col <- c("greenyellow","chartreuse4","gold",
         "darkgoldenrod1","orange","orangered3","red")
lab <- c("up to 0.1","up to 0.3","up to 0.6",
         "up to 0.8","up to 0.9","up to 1","1 and more")

dfcol <-cbind.data.frame(lab,col) %>%
  mutate(lab = factor(lab, levels = lab)

Second step:

I plot with this code:

ggplot()+
  geom_sf(data = dfgeo,aes(fill = lab)) +
  scale_fill_manual(values = col,
                    limits = brk[1:7],
                    labels = lab ) +
  theme_void()

Result is:

I see my factor Variable lab in the legend.

I see my map with the borders of all counties I'm interessed in.

But the counties are not filled with any colour I assigend to the the factor variable lab.

What is my mistake?

Thank you for any help!

1

1 Answers

1
votes

One possible solution is to make a full merge of your both dataframes in order to have all values displayed:

library(dplyr)
DF <- full_join(dfgeo, dfcol)

library(ggplot2)
ggplot(data = DF,aes(fill = lab))+
  geom_sf() +
  scale_fill_manual(values = col)

enter image description here

Does it answer your question ?