简体   繁体   English

Plot 并在 for 循环中使用 ggplot() 保存多个栅格

[英]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.我正在尝试打开 plot 并将多个栅格保存到图像文件中。 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'.我相信它与'fill = sp.n'有关。 Do you have an idea of what I am doing wrong?你知道我做错了什么吗?

While running the code in the loop, your "sp.n" is a character, while ggplot2 takes the bare unquoted name sp.n .在循环中运行代码时,您的"sp.n"是一个字符,而ggplot2采用未加引号的裸名称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]]相反,您应该使用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 "您可以在“使用 dplyr 编程”中了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM