Home > Blockchain >  Variable legend values and colors in GGPLOT
Variable legend values and colors in GGPLOT

Time:04-01

I've been omitting I problem I have regarding the production of maps though different columns. Let's say I have a certain dataset, where every row is a polygon:

> crops <- data.frame(pol_num = c("1", "2", "3","4"),
wheat2020 = c("yes", "yeswater", "yes","no"),
wheat2030 = c("yeswater", "no", "no","no"))

> crops
  pol_num wheat2020 wheat2030
1       1       yes  yeswater
2       2  yeswater        no
3       3       yes        no
4       4        no        no

As you see I have 4 polygons and the suitability of a crop in 2 years. I want to plot these polygons in ggplot with custom colors for each possibility ("yes", "yeswater" and "no").

The only solution I found is to order each column in a certain order:

crops$wheat2020 <- factor(crops$wheat2020, levels = c("yes", "yeswater","no"))

And creat a custom palette with the order of colors I need:

palette <-c("#98E601", "#72DFFE", "#A80100")

And then apply scale_fill_manual. This gets really tricky because each scenario has different possible combinations. In the example you can see how wheat2020 has 3 different values whereas wheat2030 only 2!

The code, simplified, for my plot and a certain scenario is:

ggplot()   
  geom_sf(data = crops, aes(fill = wheat2020), lwd = 0.001)  
  scale_fill_manual(labels=c("Yes", "Yes water","No"),
                    name="Suitability wheat: 2020",
                    values = palette)

Is there any way to simply indicate which color must correspond each value in the columns, no matter if there is one or two of the possible values missing?

Thanks!

CodePudding user response:

I have created some simple geometry to emulate your data frame better, but essentially all you need is to pass your color values as a named vector:

ggplot()   
  geom_sf(data = crops, aes(fill = wheat2020), lwd = 0.001)  
  scale_fill_manual(name = "Suitability wheat: 2020",
                    values = c(yes      = "#98E601", 
                               yeswater = "#72DFFE", 
                               no       = "#A80100"))

enter image description here

ggplot()   
  geom_sf(data = crops, aes(fill = wheat2030), lwd = 0.001)  
  scale_fill_manual(name = "Suitability wheat: 2030",
                    values = c(yes      = "#98E601", 
                               yeswater = "#72DFFE", 
                               no       = "#A80100"))

enter image description here

  • Related