Search code examples
rfor-loopggplot2raster

Plot and save of multiple rasters using ggplot() in a for loop


I am trying to open, plot and save multiple rasters into image files. For this, I wrote this script:

library(raster)
library(rgdal)
library(ggplot2)
library(dplyr)

species <- read.csv(file = 'C:/species.csv', sep=";")

for (sp.n in colnames(species)) {

    rsts <- raster(paste('C:/rasters/', sp.n, '.grd', sep=''))
       
    rsts_df <- as.data.frame(rsts, xy = TRUE)

    names(rsts_df)[3] <- sp.n

    ggplot() +
    geom_raster(data = rsts_df, aes(x = x, y = y, fill = sp.n), na.rm = TRUE) +
    scale_fill_gradient(low = "white", high = "violetred4") +
    coord_quickmap()

    ggsave(paste('C:/imgs/', sp.n, '.png', sep=''))
}

However, I get this message:

Error: Discrete value supplied to continuous scale

The thing is, if I do the plots individually for each raster, outside the loop, it works. I believe it has something to do with the 'fill = sp.n'. Do you have an idea of what I am doing wrong?


Solution

  • While running the code in the loop, your "sp.n" is a character, while ggplot2 takes the bare unquoted name sp.n. For instance, if you run the code:

    library(ggplot2)
    ggplot() +
    geom_raster(data = rsts_df, aes(x = x, y = y, fill = "col.name"), na.rm = TRUE)
    

    you will probably get the same error. Instead you should use fill = .data[[sp.col]]

    ggplot() +
    geom_raster(data = rsts_df, 
                aes(x = x, y = y, fill = .data[[sp.n]]), 
                na.rm = TRUE)
    

    This is all based on the concept of tidy evaluation. You can read more about it on "Programming with dplyr"