0

building my path in R, So I am still very bad especially in running loops and complexes functions...

What I am interested about is to automatically read a series of rasters in a particular folder and generate a simple ggplot visualization out of it (for each one of the rasters). Possibly exporting it to some folder would be also nice.
The further idea would be to overlap these visualizations and create an animated GIF, but this I can perhaps do outside of R... Just creating the maps would already be really nice...

With this I can load all rasters in my R enviroment:

myfiles  = list.files(pattern = "*.asc")
for (i in 1:length(myfiles)) assign(myfiles[i], raster::raster(myfiles[i]))

While the basic ggplot code to build one of the map would be:

#Loading an example raster
hflow =  raster::raster("D:/R.avaflow_graphs/Erla_E1_F01_results/Erla_E1_F01_ascii/Erla_E1_F01_hflow0000.asc")

hflow_spdf <- as(hflow, "SpatialPixelsDataFrame") # Creating a spdf
hflow_df <- as.data.frame(hflow_spdf)             # Creating a df
colnames(hflow_df) <- c("value", "x", "y")        # Assign x,y,values
ggplot() +                                        # plotting the map
geom_tile(data=hflow_df, aes(x=x, y=y, fill=value), alpha=0.8) + 
  coord_equal()  

For inspiration, I've been checking these 3 links, but still couldn't make it happen... R apply raster function to a list of characters https://gis.stackexchange.com/questions/377444/plotting-a-raster-stack-with-ggplot2 https://www.r-bloggers.com/2020/07/writing-functions-to-automate-repetitive-plotting-tasks-in-ggplot2/

Thanks beforehand! PL

Pedro Lima
  • 15
  • 4
  • You can use `ggsave()` to save each created plot within the for-plot. You just have to make sure that the filename will change within each loop, so the file is not overwritten. Note that it would be nice to read in the files without the use of assign, e.g. `for (i in 1:length(myfiles)) { myFile2plot <- raster::raster(myfiles[i])) ... plotting ... saving }` – JKupzig Dec 15 '21 at 16:17
  • Ouch @JKupzig, thanks for the comment, but I still cannot make it. As I mention, I am still new on the whole R thing... Would appreciate if you could ellaborate more or send some more material to explore. Thanks again! – Pedro Lima Dec 15 '21 at 16:28

1 Answers1

0

The first part can be easily done with a simple sapply to create a plot for each image and save it to disk using ggsave. The gif creation can also be done inside R using the magick package. You just need to read the exported plots as images, then perform a join, animate and export as gif. Here's the code to perform the complete procedure.

library(magick)
library(ggplot2)

# List all raster files
myfiles  = list.files(pattern = "*.asc")

# Loop to create plots for each image
sapply(myfiles, function(x){
  # Get image names
  im_name <- gsub("\\.[A-z]+$", "", x)
  
  # Load image as raster
  im <- raster::raster(x)
  # Transform to df
  hflow_spdf <- as(im, "SpatialPixelsDataFrame") # Creating a spdf
  hflow_df <- as.data.frame(hflow_spdf)             # Creating a df
  colnames(hflow_df) <- c("value", "x", "y")        # Assign x,y,values
  
  # Make plot
  ggplot() +                                        # plotting the map
    geom_tile(data=hflow_df, aes(x=x, y=y, fill=value), alpha=0.8) + 
    # Added fill_distiller to define filling palette
    scale_fill_distiller(type = "seq",
                      palette = "Greys") +
    coord_equal()  
  
  # Save plot
  ggsave(paste0(im_name, ".png"),
         device = "png",
         width = 10,
         height = 10,
         units = "cm",
         dpi = 150)
})

# Create gif
# List plots files
plots <- list.files(pattern = ".png")
# Read the plots as image
plots_list <- lapply(plots, image_read)

# Join the list of plots
plot_joined <- image_join(plots_list)

# Create animation, defining the frames per second (fps)
plot_animated <- image_animate(plot_joined, fps = 1)

# Write animation as gif
image_write(image = plot_animated,
            path = "plots_anim.gif")