'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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source