我正在尝试学习如何在R-Studio和笔记本中导入,显示和处理geo-tiff文件。当我运行代码时,我没有收到任何错误。未显示绘图,但在控制台中输入绘图名称会出现错误。就好像检测到错误,仍然创建了绘图,但运行块或运行"编织"都没有报告错误。
fimage_plot Error: Discrete value supplied to continuous scale
我的代码块:
rlist <- list.files(tiffTestFldrOrig, pattern="tif$",
full.names=TRUE)
for(tiff_path_nane in rlist) {
fimage <- raster(tiff_path_nane)
fill_col_name = names(fimage)
fimage_df <- as.data.frame(fimage, xy = TRUE)
fimage_plot <- ggplot() +
geom_raster(data = fimage_df, aes(x=x, y=y,
fill = fill_col_name)) +
scale_fill_continuous(type = "gradient") +
coord_quickmap()
fimage_plot # no plot displayed, no error
break() # until error corrected
}
我尝试过谷歌,搜索各种scale_fill_discete
,scale_fill_continous
等,但无济于事。
顺便说一句,我的x&y数据是UTM,第三列16位整数值代表野火的温度。
好的@Nate我通过自己生成示例数据粗略地做了一些事情。希望它有效,这就是你想要的:
library(raster)
library(ggplot2)
r1 <- raster(nrows = 1, ncols = 1, res = 0.5,
xmn = -1.5, xmx = 1.5, ymn = -1.5, ymx = 1.5, vals = 0.3)
fimage <- lapply(1:10, function(i) setValues(r1,runif(ncell(r1))))
fimage_plot <- list()
for(i in 1:length(fimage)) {
fimage_df <- as.data.frame(fimage[[i]], xy = TRUE)
fimage_plot[[i]] <- ggplot(fimage_df, aes(x, y)) +
geom_raster(aes(fill = layer)) +
guides(fill=guide_legend(title=paste0("Plot ", i))) # if you want to change the legend
fimage_plot[[i]]
# break() # until error corrected
}
这不起作用,因为在:
geom_raster(data = fimage_df, aes(x=x, y=y, fill = fill_col_name))
您正在使用字符变量来指定填充。ggplot
不喜欢这样。
您可以避免更改fimage
的名称,然后使用
geom_raster(data = fimage_df, aes(x=x, y=y, fill = layer))
如@Majid回复,或使用aes_string
将字符变量关联到fill
:
geom_raster(data = fimage_df, aes_string(x="x", y="y", fill = fill_col_name))
(但请注意,aes_string
是软弃用的:将来它可能会停止工作,你将不得不使用整洁的评估。
呵呵