0
votes

Hy everyone! I really need some help to create a discrete legend over a continuous map.

Here what I have so far: Here you see probability of occurrence of a plant species accordingly to 4 statistical algos. In the legend you see "0,1,2,3,4", but legend values are categorical, but legend colour palete stills works under continuous values, with colours not properly separeted.

However, what I want is a categorical legend with continuous values from the map according the each category in the legend, aiming to clearly indicate the accordance betweenn algorithms prediction, with no continuous scale.

Image 2 you see the perfect map, but I want to make it using ggplot2: Here I can clearly indicate in the discrete legend the colors accordingly to the 4 statistical algos.

For the second map I used the code below:

 breakpoints <- c(-125,125,375,625,875,1125)
   colors <- c(grey(seq(0.9,0.7,-0.2)),gcolors(3))
   a.arg <- list(at=seq(0,1000,length.out=5), labels=c("0","1","2","3","4"),cex.axis=1.5)
   l.arg <- list(text="Vote",side=2, line=0.5, cex=1.5)

  par(mar=c(0,0,0,r.mar),cex=1.4)
   plot(mymap,col=colors,ext=study_area, breaks=breakpoints,
   legend.width=1.5,legend.shrink=0.6,legend.mar=7,
   axis.args=a.arg,legend.arg=l.arg,
   axes=FALSE, box=FALSE, zlim=c(0,1000))

And it works perfectly!

However, under ggplot2 I was using this piece of code:

 #Color scales pres 
 col_scale_var_test_pres <- scale_fill_gradientn(
   colours = c(grey(c(0.90,seq(0.9,0.7,-0.2))),gcolors(3)), # colour palete
   na.value="transparent",
   values=rescale(seq(0,1000),0,1000), 
   limits=c(0,1000),
   breaks= seq(0,1000,by=250), # if one algo predict species occurrence it counts 250, two algos 
   #(500), ### three (750), four (1000)
   labels= c(0,1,2,3,4)
  )

  b1 <- plot_anomaly_2(r= species_map, label="(b)",title="") + col_scale_var_test_pres

I already tried to use #scale_fill_manual, #scale_fill_gradientn etc. and also fallowed this question (which is quite similar): R ggplot2 discrete colour palette for gradient map. But I still can't solve this.

Any help and suggestion will be greatly appreciated!

1

1 Answers

0
votes

A reproducible code might be more useful next time. Assuming you want to plot data from mymap dataframe, then the following code might be helpful:

library(tidyverse)
library(ggthemes)
mymap %>%
  mutate(value = cut(data,
                     breaks = c(-125,125,375,625,875,1125), right = FALSE,
                     labels = c("0", "1", "2", "3", "4", "5"))) %>%
  ggplot(., aes(x = long, y = lat, group = group, fill = value)) +
  geom_polygon(col = "grey") + scale_fill_brewer(palette = "YlGnBu", direction = 1) +
  coord_fixed(xlim = c(-130, 1200)) + theme_map() + 
  theme(legend.position = "bottom")