Search code examples
rggplot2legendrastershapefile

How to make continuous legend in ggplot2?


I have little query regarding the legend in ggplot2. How can I make legend in a continuous level from the attached code. In this code the legend is in discrete form I want to make it in continuous form (smooth continuous pattern) The code is reproducible ( little bit long but probably one line will change in this code)

 library(sf)
 library(sp)

 r <- raster(t((volcano[,ncol(volcano):1] - 94) * 4.95))

 # Let's mock with a shapefile
 poly <- st_as_sfc(st_bbox(st_as_sf(rasterToPolygons(r))))

 # Sample 4 points
 set.seed(3456)

 sample <- st_sample(poly, 4)
 sample <- st_buffer(sample, c(0.01, 0.02, 0.03))
 sample <- st_sf(x=1:4, sample)
 st_write(sample, "1aa.shp", append = FALSE)
 # Mocked data

 # Now let's start with code -------

 r <- raster(t((volcano[,ncol(volcano):1] - 94) * 4.95))

 # Use sf!!
 pg <- st_read("1aa.shp") # loadshapfile 
 plot(r)
 plot(st_geometry(pg), add= TRUE,) # it appears here like first picture 
(left).

 centile90 <- quantile(r, 0.90)
 df <- as.data.frame(as(r, "SpatialPixelsDataFrame"))
 colnames(df) <- c("value", "x", "y")

 library(ggplot2)

  mybreaks <- seq(0, 500, 50)

  ggplot(df, aes(x, y, z = value)) +
  geom_contour_filled(breaks = mybreaks) +
  geom_contour(breaks = centile90, colour = "pink",
             size = 0.5) +
   # And here we have it
   geom_sf(data=pg, fill="black", inherit.aes = FALSE) +
  scale_fill_manual(values = hcl.colors(length(mybreaks)-1, "Zissou1", rev 
  = FALSE)) +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0)) +
  theme_classic() +
  theme()

After run this code I got legend in this form (left side of attached picture) ,means discontinuous, but I want to make this legend look like (right side of attached picture). But in my code I give the command of continuous scale. Can someone tell me how to make this code for required legend smooth continuous pattern.

enter image description here


Solution

  • You could use the function geom_tile and scale_fill_gradientn to get a continuous scale instead of discrete scale legend like this:

    library(ggplot2)
    library(sf)
    library(sp)
    library(raster)
    mybreaks <- seq(0, 500, 50)
    
    ggplot(df, aes(x, y, fill = value)) +
      geom_tile() +
      scale_fill_gradientn(
        colours = hcl.colors(length(mybreaks)-1, "Zissou1", rev = FALSE), 
        breaks = mybreaks
      ) +
      geom_sf(data=pg, fill="black", inherit.aes = FALSE) +
      scale_x_continuous(expand = c(0, 0)) +
      scale_y_continuous(expand = c(0, 0)) +
      theme_classic() +
      theme()
    

    Output:

    enter image description here