【问题标题】:ggplot label contours with sf object带有sf对象的ggplot标签轮廓
【发布时间】:2021-10-30 10:30:27
【问题描述】:

我有一个使用 st_read() 从 shapefile 导入的轮廓数据集。我使用ggplot()geom_sf() 绘制了这个图。它渲染得很好。现在我想标记轮廓。使用geom_st_label() 不会产生很好的输出。轮廓处处密集,标签重叠。

我查看了metR 包。这有一个geom_contour_label() 函数,可以很好地控制ggplot() 中的轮廓放置。但是,geom_contour() 和相关函数无法识别 sf_objects 中包含的几何图形。我收到此错误:stat_contour requires the following missing aesthetics: x, y and z

如何让geom_contour_label() 使用 sf 对象?这是geom_contour_label() 可以产生的:

我的轮廓数据可从https://cloudstor.aarnet.edu.au/sender/?s=download&token=241de91b-2015-4a19-a18f-c2125a12f2a7获得。

library(sf)
library(tidyverse)

isobath <- read_sf("1misobath.shp")

ggplot() +
  geom_sf(data = isobath, color = "blue", lwd = 0.25) +
  geom_sf_label(data = isobath, aes(label = DEPTH), size = 2) +
  coord_sf(xlim = c(18.42, 18.5), ylim = c(-34.20, -34.16), expand = T) +
  theme_bw()

【问题讨论】:

  • 嗨@aterhorst。不知道我是否可以帮助你,但目前我无法下载文件;-)
  • 固定下载链接。
  • 我查看了st_coordinates(),可以提取 XY 坐标以及相应的线串标识符。为什么geom_contour() 无法处理 sf 对象令人费解。
  • 感谢您的链接。明天我会详细研究这个(目前,在法国已经很晚了,我的神经元断开了!!)。干杯。
  • 嗨@aterhorst。经过几个小时的彻底检查/测试,我认为我已经找到了解决您的映射问题的令人满意的解决方案(参见下面的答案)。我希望它会满足你的愿望。干杯。

标签: r ggplot2 sf


【解决方案1】:

在深入检查了geom_contour() 函数之后。这是我对问题的理解。

函数geom_contour() 不需要sf 类型的对象,而是dataframedata.table,其中包含三列点的行(不是您的情况下的线串):经度(即X) ,纬度(即 Y)和 Z 列(即,在您的情况下,这将是变量 DEPTH)。然后geom_contour() 函数将计算等值线并将它们绘制在地图上。

从您的sf 对象中,我能够创建一个具有 X、Y 和 Z 坐标的点的数据框,正如函数所期望的那样,但后来我遇到了一个无法解决的问题。您的数据网格是rectilinear,但该函数需要regular 类型的网格。因此,要将网格从rectilinear 转换为regular,我尝试使用akima 包的interp() 函数对点进行插值,但由于Z 中的重复值(即变量DEPTH )。

所以我改变了主意!最后,我想我通过使用非常好的 tmap 包的 tm_iso() 函数找到了一个非常简单的映射问题解决方案。

请在下面找到显示代码和生成的地图结果的代表。

Reprex

library(sf) 
library(s2)
library(tmap)

# 1. Your data
isobath <- st_read("D:/test/Projet_essai4/Isobath/1misobath.shp")
#> Reading layer `1misobath' from data source 
#>   `D:\test\Projet_essai4\Isobath\1misobath.shp' using driver `ESRI Shapefile'
#> Simple feature collection with 162 features and 9 fields
#> Geometry type: LINESTRING
#> Dimension:     XY
#> Bounding box:  xmin: 18.43944 ymin: -34.19143 xmax: 18.49996 ymax: -34.16805
#> Geodetic CRS:  Cape


# 2. Visualization of your data with tm_iso() of the tmap package
tm_shape(isobath) +
  tm_grid(col ="lightgray", line = TRUE) +
  tm_iso(col = "blue", text = "DEPTH",  fontface = "bold") +
  tm_layout(frame = TRUE, inner.margins = 0) 

reprex package 创建于 2021-10-31 (v0.3.0)

  • 另一个版本,可能更接近您正在寻找的内容:
tm_shape(isobath) +
  tm_grid(col ="white", line = TRUE) +
  tm_iso(col = "blue", text = "DEPTH",  fontface = "bold", bg.color = "lightgray", shadow = TRUE, size = 0.6) +
  tm_layout(bg.color = "lightgray", frame = TRUE, inner.margins = 0) 

reprex package (v0.3.0) 于 2021 年 10 月 31 日创建

【讨论】:

    猜你喜欢
    • 2015-05-31
    • 1970-01-01
    • 2015-07-27
    • 2021-04-07
    • 1970-01-01
    • 2022-01-24
    • 2020-03-17
    • 2016-01-12
    相关资源
    最近更新 更多