R用ggplot2耗尽内存绘制数据帧

时间:2020-05-01 01:12:46

标签: r linux ggplot2 r-raster

我正在具有8Gb RAM的Dell XPS笔记本电脑的Fedora 31上运行R。我试图使用ggplot2绘制Playground link to code,以便可以使用已经用ggplot2编写的代码覆盖其他数据。我大致遵循this GeoTIFF来处理R中的栅格数据。将TIFF转换为RasterLayer转换为数据帧后,使用ggplot2加载数据帧时,R程序失败,仅输出“ Killed”并退出

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

createTypedArray()

运行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)) 显示R用完了内存:

dmesg

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

我对R比较陌生,所以如果我忽略了这里的明显内容,请原谅我。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

我无法说出ggplot的存储要求,但是数据的空间分辨率非常高(〜90m)。要求ggplot绘制10955(行)* 17267(列)= 189,159,985像素没有意义,因为您将看不到它们(除非您正在打印广告牌)。因此,一个简单的解决方法是获取常规样本或汇总

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软件包中,还有更好的选项可以制作地图。

相关问题