R使用ggplot2绘制数据帧时内存不足



我在Fedora 31上运行R,运行在8Gb RAM的Dell XPS笔记本电脑上。我正试图使用ggplot2绘制这个GeoTIFF,这样我就可以使用我已经用ggplot2编写的代码覆盖其他数据。我大致遵循了这节关于在R中处理光栅数据的课程。将TIFF转换为RasterLayer并转换为数据帧后,R程序在使用ggplot2加载数据帧时失败,只需输出"Killed"并退出即可。

以下是产生此错误的最小代码示例:

library(tidyverse)
library(raster)
library(rgdal)
afg_pop <- raster("afg_ppp_2020.tif")
pop_df <- as.data.frame(afg_pop, xy = TRUE)
ggplot() +
# This is the line that results with the error: "Killed"
geom_raster(data = pop_df , aes(x = x, y = y, fill = afg_ppp_2020))

运行dmesg显示R内存不足:

[20563.603882] Out of memory: Killed process 42316 (R) total-vm:11845908kB, anon-rss:6878420kB, file-rss:4kB, shmem-rss:0kB, UID:1000 pgtables:19984kB oom_score_adj:0

我很难相信,即使有一个数据文件,这么大的R也会耗尽处理它所需的内存。为什么R需要这么多内存来执行这项任务,更重要的是,我还可以使用什么其他方法来绘制这些数据,最好是使用ggplot2?

我对R还比较陌生,所以如果我忽略了一些明显的东西,请原谅我。任何帮助都将不胜感激!

我无法谈论ggplot的内存需求,但数据的空间分辨率非常高(~90m(。要求ggplot绘制10955(行(*17267(列(=189159985像素是没有意义的,因为你看不到它们(除非你正在打印广告牌(。因此,一个简单的解决方法是采取常规样本,或聚合

f <- "ftp://ftp.worldpop.org.uk/GIS/Population/Global_2000_2020/2020/AFG/afg_ppp_2020.tif"
if (!file.exists(basename(f))) download.file(f, basename(f), mode="wb")
library(raster)
afg_pop <- raster("afg_ppp_2020.tif")
pop_df <- data.frame(sampleRegular(afg_pop, 10000, xy=TRUE))
library(ggplot2)
ggplot() + geom_raster(data = pop_df , aes(x = x, y = y, fill = afg_ppp_2020))

一个更好的替代方案,需要更长的

afg_pop2 <- aggregate(afg_pop, 10) # this takes some time
pop_df2 <- as.data.frame(afg_pop2, xy=TRUE)
ggplot() + geom_raster(data = pop_df2 , aes(x = x, y = y, fill = afg_ppp_2020))

地图不是很好看;在其他R包中有更好的选项用于制作地图。

最新更新