Search code examples
rggplot2contourcontourfgeom-raster

plotting contours in ggplot - geom_raster, geom_contour, geom_point


I have an interpolated dataset that I want to plot. When I plot it as geom_point, I see a lot of features that I am missing when I use geom_raster or geom_contour. Im guessing it got smoothed over? Is there a way I can plot this without losing the finer grain contours picked up in the geom_point? and the second figure looks terrible! is there a way to smooth this?

ggplot() + geom_raster(data = df, 
                             aes(x=X, y = Y, fill=Z)) + scale_y_reverse() +
scale_fill_distiller(palette = "RdYlBu") +
theme_bw() + theme(panel.grid = element_blank()))


 ggplot(data=df, aes(x = X, y = Y)) +
  geom_point(aes(colour = Z)) + scale_y_reverse() +
scale_colour_gradientn(colours = rev(ODV_colours)) +
theme_bw() + theme(panel.grid = element_blank()))

Solution

  • It seems that you have a low resolution raster and you want to interpolate to make this less blocky. You could use interp for 2-D interpolation in this instance:

    library(interp)
    library(ggplot2)
    
    ODV_colours <- c('#fca878', '#d42b28', '#fbbf00', '#2cab1a', 
                     '#19b3e6', '#6f44fc', '#c767fa')
    
    
    interp(x = df$X, y = df$Y, z = df$Z, nx = 1000, ny = 1000, linear = FALSE) |> 
      interp2xyz() |>
      as.data.frame() |>
      ggplot(aes(x, y, fill = z)) +
      geom_raster() +
      scale_y_reverse() +
      scale_fill_gradientn(colours = rev(ODV_colours), na.value = NA) +
      theme_bw(base_size = 16) + 
      theme(panel.grid = element_blank())
    

    enter image description here