如何使用ggplot投影栅格和观察点

问题描述 投票:0回答:1

他全部!我是R世界的新手,我认为这将是一个愚蠢的错误:我想投影一个代表我的“研究区域”的栅格,并添加从rgbif中获得的观察结果。

首先,我使用多边形在“研究区域”中进行了实物观察:

    wkt<-'POLYGON((14.022120 41.583456,13.928857 41.610301,13.607180 41.789949,13.645924 42.021854,13.779864 42.029311,14.035472 41.823996,14.066175 41.751961,14.057895 41.614899,14.022120 41.583456))'
    Picus_viridis<-occ_data(scientificName = "Picus viridis",geometry = wkt, return = "data", limit = 1999)
    Picus_viridis<-Picus_viridis$data

# Second, I've upload the raster, cropped it to the extension of interest and assigned a projection:

    elev<-raster("data/gtopo30/gtopo30.tif")
    elev_park<-crop(elev, extent(13.398953, 14.235655, 41.402820, 42.064252))
    projection(elev_park)<-"+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"

# Than I've tried to plot the raster with the observation points using ggplot but R said me the there is an error:

    ggplot() +
  geom_raster(elev_park, aes(x = x, y = y)) +
  geom_point(aes(x = Picus_viridis$decimalLongitude, y = Picus_viridis$decimalLatitude))

Errore: `mapping` must be created by `aes()`

有人知道这是问题吗?

r ggplot2 raster r-raster
1个回答
0
投票

没有您的数据集,我无法确认这是否全部可行,但是ggplot用法的一般结构是:

  • ggplot()调用中,应提供数据集和映射。您不需要have来执行此操作,但这通常是一个好主意,除非您使用管道命令(%>%)或类似的命令。您的基地mapping=几乎总是也提供在那里。可以将此功能视为“根本不用数据创建基本图”。

  • 所有geom_函数(据我所知)的参数设置以mapping=,然后data=和其他参数开头。这意味着,如果您未显式声明结构,则第一个参数将应用于mapping=。这就是为什么您的geom_raster(elev_park,...)将引发错误。

  • 通常,最佳做法是将几何data作为数据集发送,并将映射作为列名发送-不命名向量。因此,您可以将其设置为x=my_dataset$column1data=my_dataset,而不是mapping=aes(x=column1...)

话虽这么说,但我建议的修订应该会在下面给出。假设存在elev_park$xelev_park$y。如果不是,请使用正确的列名(未引用)替换x=y=映射。

ggplot(elev_park, aes(x=x, y=y)) +
  geom_raster() +     # mapping not needed.  It's passed from ggplot()
  geom_point(         # should be explicit when setting mapping and data
    data=Picus_viridis,
    mapping=aes(x=decimalLongitude, y =decimalLatitude)
  )
© www.soinside.com 2019 - 2024. All rights reserved.