Search code examples
rggplot2raster

How to apply break in ggplot?


I have a raster data which ranges from 0 to 500. I have applied the centile on my data and my codes is shown below. I want to apply the breaks on my code like because sometime i needs values only ranges from 200-500 so without sequence option and breaks I can't do this.

     **breaks = seq (0, 500, 50), limits = c(0, 500))+** # But I don't get where can i apply this in my code

I want to apply breaks after every 50 like 0-50, 50-100 and so on....

      r <- raster("D:/research.tif")
      centile90 <- quantile(r, 0.95)
      df <- as.data.frame(as(r, "SpatialPixelsDataFrame"))
      colnames(df) <- c("value", "x", "y")


      ggplot(df, aes(x, y, z = value)) +
      geom_contour_filled(bins = 8) +
      geom_contour(breaks = centile90, colour = "orange",
           size = 0.5) +
      scale_fill_manual(values = hcl.colors(8, "YlGnBu", rev = TRUE)) +
      scale_x_continuous(expand = c(0, 0)) +
      scale_y_continuous(expand = c(0, 0)) +
      theme_classic() +
       theme()

Solution

  • You can pass the vector of breaks to the breaks argument of geom_contour_filled.

    Let's first create a raster with values from 0 to 500

    library(raster)
    
    r <- raster(t((volcano[,ncol(volcano):1] - 94) * 4.95))
    
    range(r[])
    #> [1]   0.00 499.95
    
    df <- as.data.frame(as(r, "SpatialPixelsDataFrame"))
    colnames(df) <- c("value", "x", "y")
    

    Now we call the plot like this:

    centile90 <- quantile(r[], 0.9)
    
    # Define breaks vector
    mybreaks <- seq(0, 500, 50)
    
    ggplot(df, aes(x, y, z = value)) +
      geom_contour_filled(breaks = mybreaks) +
      geom_contour(breaks = centile90, colour = "orange",
                   size = 0.5) +
      scale_fill_manual(values = hcl.colors(length(mybreaks) - 1, "YlGnBu", rev = TRUE)) +
      scale_x_continuous(expand = c(0, 0)) +
      scale_y_continuous(expand = c(0, 0)) +
      theme_classic() +
      theme()
    

    enter image description here