R mapbox / 带有动画和 shapefile 的绘图

2024-05-02

我正在制作一个动画,显示地图上绘制的空间数据,并带有基于日期的动画滑块。除此之外,我想绘制一个随时间变化的形状文件。 我的动画在没有 shapefile 的情况下也能正常工作。绘制标记和形状文件不会显示形状文件(似乎是两者之间的某种脱节add_sflayout我不明白的规格),并且还破坏了动画。如何才能使这些协同工作?我想我需要坚持plot_ly规范(相对于plot_mapbox)使我的实际情节的其他组成部分一起工作(here https://stackoverflow.com/questions/77145055/r-plotly-display-image-on-hover-in-a-map/77145696?noredirect=1#comment136069467_77145696 and here https://stackoverflow.com/questions/76906457/plotly-map-and-plot-with-shared-animation).

library(sf)
library(dplyr)
library(plotly)

nc <- st_read(system.file("shape/nc.shp", package="sf")) %>%
      select(AREA) %>%
       sf::st_cast("MULTILINESTRING") %>%
       sf::st_cast("LINESTRING")
df <- expand.grid(x = seq(-76, -84, -2), y = seq(34, 36, 1),
                  Date = seq(as.Date("2000-01-01"), as.Date("2000-04-01"), by = "1 day")) %>%
      mutate(x = rnorm(n(), x, 1),
              y = rnorm(n(), y, 1),
             Date = as.factor(Date))


df %>%
  plot_ly(lon = ~x, lat = ~y, frame = ~Date, 
          type = "scattermapbox", mode = "markers") %>%
  ######### this line breaks the animation and doesn't show the sf. Uncomment to check
  #########add_sf(data = nc, inherit = FALSE, color = I("white")) %>%
  layout(mapbox = list(style = "white-bg", sourcetype = 'raster', zoom = 4,
                     center = list(lon = -80 ,lat= 35),
                     layers = list(list(below = 'traces', sourcetype = "raster",
                                        source = list("https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"))))) 

Add-On

要更改跟踪的顺序,必须做两件事:文字跟踪顺序和分配给每个帧的跟踪索引。我原来的答案中的所有内容仍然适用,但代替fixer(), 这是fixer2()

fixer2 <- function(plt1, plt2) {
  # change the order of the traces (considering fixer())
  # where plt1 has frames and plt2 does not
  # get lines' trace from plt2, add to plt1 as the first trace
  # change the 'trace' index in each frame in plt1$x$frames
  plt1 <- plotly_build(plt1); plt2 <- plotly_build(plt2)  # prep by building
  lines2 <- lapply(1:length(plt2$x$data), function(i) {
    if(plt2$x$data[[i]]$mode == "lines") {   # extract index for combined plot
      return(i)
    }
  }) %>% unlist()
  plt1$x$data <- append(plt2$x$data[lines2], plt1$x$data) # add data diff order
  lapply(1:length(plt1$x$frames), function(j) {    # change frames trace index
    plt1$x$frames[[j]]$traces <<- 1 + plt1$x$frames[[j]]$traces
  }) # this assumes scatter is one color
  plt1   # return modified plot
}
fixer2(p1, p2)

原始答案(附加组件之前)

我猜您正在寻找的是动画期间北卡罗来纳州各县的静态轮廓。如果这是一个准确的假设,那么这将起作用。我尝试了几种不同的方法,因为我不明白为什么 Plotly 在翻译中如此迷失。但是,我只能通过解决方法使其正常运行(而不是绘图参数或类似的东西)。

首先,我将向您展示我的解决方案。

然后我有一个你可知道? and a 也许这看起来会好一点,如果......

The plot

我创建了两个scattermapbox绘图并将它们与 UDF 结合起来。我基本上使用了你的代码,但两者都做了scattermapbox(相对于一个scattermapbox和一个add_sf).

library(sf)
library(dplyr)
library(plotly)

nc <- st_read(system.file("shape/nc.shp", package="sf")) %>%
  select(AREA) %>%
  sf::st_cast("MULTILINESTRING") %>%
  sf::st_cast("LINESTRING")

df <- expand.grid(x = seq(-76, -84, -2), y = seq(34, 36, 1),
                  Date = seq(as.Date("2000-01-01"), as.Date("2000-04-01"), by = "1 day")) %>%
  mutate(x = rnorm(n(), x, 1),
         y = rnorm(n(), y, 1),
         Date = as.factor(Date))


p1 <- plot_ly(data = df, lon = ~x, lat = ~y, frame = ~Date, 
              type = "scattermapbox", mode = "markers") %>%
  layout(mapbox = list(style = "white-bg", sourcetype = 'raster', zoom = 4,
                       center = list(lon = -80 ,lat= 35),
                       layers = list(list(below = 'traces', sourcetype = "raster",
                                          source = list("https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"))))) 

p2 <- plot_ly(data = nc, type = "scattermapbox", color = I("white")) %>%
  layout(mapbox = list(style = "white-bg", sourcetype = 'raster', zoom = 4,
                       center = list(lon = -80 ,lat= 35),
                       layers = list(list(below = 'traces', sourcetype = "raster",
                                          source = list("https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"))))) 

在 UDF 中,我采用lines追踪从data = nc绘制并将该数据添加到另一个图中。

fixer <- function(plt1, plt2) {
  # where plt1 has frames and plt2 does not
  # get lines' trace from plt2
  # add lines' trace data to plt1$x$data 
  plt1 <- plotly_build(plt1); plt2 <- plotly_build(plt2)  # prep by building
  lines2 <- lapply(1:length(plt2$x$data), function(i) {
    if(plt2$x$data[[i]]$mode == "lines") {   # extract index for combined plot
      return(i)
    }
  }) %>% unlist()
  plt1$x$data <- append(plt1$x$data, plt2$x$data[lines2]) # add data to plt1
  plt1   # return modified plot
}
fixer(p1, p2)

你可知道?

您做了一些额外的工作nc数据,使用select and st_cast。然而,这项工作并没有改变任何东西......我不确定目标是什么。

要创建相同的地图,您可以按原样保留数据并添加fill = "none"到痕迹。

这是一个直观的解释。

nc2 <- st_read(system.file("shape/nc.shp", package="sf"))

p3 <- plot_ly(data = nc2, fill = "none", type = "scattermapbox", color = I("white")) %>%
  layout(mapbox = list(style = "white-bg", sourcetype = 'raster', zoom = 4,
                       center = list(lon = -80 ,lat= 35),
                       layers = list(list(below = 'traces', sourcetype = "raster",
                                          source = list("https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"))))) 
fixer(p1, p3)

看起来可能会好一些,如果...

我注意到线条太粗,很难看到动画,所以我想我应该添加默认线条scattermapbox is line = list(width = 2)。在这个变体中,我使用了原来的nc数据并将线宽减半。 (尽管如此,它仍然很招摇。)

p4 <- plot_ly(data = nc2, fill = "none", type = "scattermapbox", color = I("white"), 
              line = list(width = 1)) %>%
  layout(mapbox = list(style = "white-bg", sourcetype = 'raster', zoom = 4,
                       center = list(lon = -80 ,lat= 35),
                       layers = list(list(below = 'traces', sourcetype = "raster",
                                          source = list("https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"))))) 
fixer(p1, p4)

所有代码一并

这里将所有代码(上面分解)集中在一个地方(更容易复制+粘贴等等)。

library(sf)
library(dplyr)
library(plotly)

nc <- st_read(system.file("shape/nc.shp", package="sf")) %>%
  select(AREA) %>%
  sf::st_cast("MULTILINESTRING") %>%
  sf::st_cast("LINESTRING")

df <- expand.grid(x = seq(-76, -84, -2), y = seq(34, 36, 1),
                  Date = seq(as.Date("2000-01-01"), as.Date("2000-04-01"), by = "1 day")) %>%
  mutate(x = rnorm(n(), x, 1),
         y = rnorm(n(), y, 1),
         Date = as.factor(Date))

#---------------------------- basic fix ----------------------------
p1 <- plot_ly(data = df, lon = ~x, lat = ~y, frame = ~Date, 
              type = "scattermapbox", mode = "markers") %>%
  layout(mapbox = list(style = "white-bg", sourcetype = 'raster', zoom = 4,
                       center = list(lon = -80 ,lat= 35),
                       layers = list(list(below = 'traces', sourcetype = "raster",
                                          source = list("https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"))))) 

p2 <- plot_ly(data = nc, type = "scattermapbox", color = I("white")) %>%
  layout(mapbox = list(style = "white-bg", sourcetype = 'raster', zoom = 4,
                       center = list(lon = -80 ,lat= 35),
                       layers = list(list(below = 'traces', sourcetype = "raster",
                                          source = list("https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"))))) 


fixer <- function(plt1, plt2) {
  # where plt1 has frames and plt2 does not
  # get lines' trace from plt2
  # add lines' trace data to plt1$x$data 
  plt1 <- plotly_build(plt1); plt2 <- plotly_build(plt2)  # prep by building
  lines2 <- lapply(1:length(plt2$x$data), function(i) {
    if(plt2$x$data[[i]]$mode == "lines") {   # extract index for combined plot
      return(i)
    }
  }) %>% unlist()
  plt1$x$data <- append(plt1$x$data, plt2$x$data[lines2]) # add data to plt1
  plt1   # return modified plot
}
fixer(p1, p2)


#---------------------- using NC data as is-------------------------
nc2 <- st_read(system.file("shape/nc.shp", package="sf"))

p3 <- plot_ly(data = nc2, fill = "none", type = "scattermapbox", color = I("white")) %>%
  layout(mapbox = list(style = "white-bg", sourcetype = 'raster', zoom = 4,
                       center = list(lon = -80 ,lat= 35),
                       layers = list(list(below = 'traces', sourcetype = "raster",
                                          source = list("https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"))))) 
fixer(p1, p3)

#----------- basic NC data & different line aesthetics -------------
p4 <- plot_ly(data = nc2, fill = "none", type = "scattermapbox", color = I("white"), 
              line = list(width = 1)) %>%
  layout(mapbox = list(style = "white-bg", sourcetype = 'raster', zoom = 4,
                       center = list(lon = -80 ,lat= 35),
                       layers = list(list(below = 'traces', sourcetype = "raster",
                                          source = list("https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"))))) 
fixer(p1, p4)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

R mapbox / 带有动画和 shapefile 的绘图 的相关文章

  • 如何使用 sprintf 函数在字符中添加前导“0”而不是空格?

    我正在尝试使用sprintf函数为字符添加前导 0 并使所有字符长度相同 然而我得到的是领先空间 My code a lt c 12 123 1234 sprintf 04s a 1 12 123 1234 我试图得到什么 1 0012 0
  • 聚合日期时间以总结在特定条件下花费的时间

    我很困惑我应该如何继续 我下面有一些虚拟数据 Date lt as POSIXct c 2018 03 20 11 52 25 2018 03 22 12 01 44 2018 03 20 12 05 25 2018 03 20 12 10
  • ggplot 图例标签内的希腊字母、符号和换行符

    我在尝试着 有换行符 自动或强制 对齐文本 左对齐或左右对齐 有希腊字母和百分号 在 gglot 图例标签内 我尝试了几种方法 但我似乎无法将我读到的所有技巧结合起来 我可以通过插入来换行 n进入标签 但这似乎不适用于希腊字母 不适用于图例
  • 在函数中使用 quit/q 会导致 RStudio 出现致命错误

    更多的是好奇 但当你使用时q or quit在 R studio 内的函数内部 它会导致致命错误 如下所示 但 rgui 中的相同函数会导致 R 像往常一样停止 并且仅使用q 在 RStudio 中按预期关闭 R 为什么q在函数中导致 RS
  • 美人鱼图:调整图表周围的空白

    我在用 Rstudio 编译的 Rmd 报告中使用了美人鱼图 在 HTML PDF 输出中 图表上方和下方有大量空白 请参见下面的示例 Header Text r library DiagrammeR mermaid graph TD cl
  • 如何有效地将多个光栅 (.tif) 文件导入 R

    我是 R 新手 尤其是在空间数据方面 我正在尝试找到一种方法来有效地将多个 600 单波段栅格 tif 文件导入到 R 中 所有文件都存储在同一文件夹中 不确定这是否重要 但请注意 在我的 Mac 和 Windows 并行 VM 上的文件夹
  • 为每个因素级别添加日期时间序列

    我有一个带有因子列的数据框 s lt data frame id 901 910 s id lt as factor s id 我有一个日期时间序列 library lubridate start lt now as difftime 2
  • R:ifelse 中的字符串列表

    我正在寻找与 MySQL 中的 where var in 语句类似的东西 我的代码如下 data lt data frame id 10001 10030 cc1 rep c a b c 10 attach data data new lt
  • 根据 R 数据框中的名称对列进行平均

    我想知道是否有一种有效的方法来获取每组的平均值类似命名的列谁的名字结尾为 1S and 2S ex ex1S ex2S at time 1并取每组的平均值类似命名的列谁的名字结尾为 1C or 2C ex ex1C ex2C at time
  • 如何在R中匹配具有相同主键的两个表中的数据

    我有两个表 其中包含有关人员的数据 df1 lt data frame id c 113 202 377 288 359 name c Alex Silvia Peter Jack Jonny 这为我提供了 id name 1 113 Al
  • zsh:未找到命令:使用 Big Sur Mac 的终端上的 R

    我从官方 cran 网站安装了 R 我可以从 Rstudio 运行 R 但是当我尝试从终端使用 R 时 我得到以下结果 base ege Eges MBP R zsh command not found R base ege Eges MB
  • R参考类问题

    我正在尝试在 R 中创建一个简单的参考类 这是我的代码 R 初学者 MyClass lt setRefClass MyClass fields list a numeric b numeric methods list initialize
  • Jupyter 笔记本中未显示绘图图表

    我已经尝试解决这个问题几个小时了 我按照上面的步骤操作情节网站 https plot ly python getting started start plotting online并且图表仍然没有显示在笔记本中 这是我的情节代码 color
  • 通过 R 中的数据子集执行计算

    我想对数据框的 PERMNO 列中的每个公司编号进行计算 其摘要可以在此处查看 gt summary companydataRETS PERMNO RET Min 10000 Min 0 971698 1st Qu 32716 1st Qu
  • rvest 和 NHL 统计数据的 CSS 选择器问题

    我想从 hockey reference com 中抓取数据 特别是从以下链接中抓取数据 https www hockey reference com leagues NHL 1991 html https www hockey refer
  • 按不规则时间间隔对数据进行分组求和(R语言)

    我正在看这里的 stackoverflow 帖子 R 计算一组内的观察次数 https stackoverflow com questions 65366412 r count number of observations within a
  • R 编程常用工具

    如果已经以不同的方式问过这个问题 我深表歉意 但我找不到任何达到我想要的东西 我真的是从其他软件包 SPSS 开始接触 R 的 当我了解真正可以做什么时 我意识到我还需要其他 工具 这让我想到了我的问题 您有哪些用于开发 R 代码的设置 我
  • 在 igraph 中为社区分配颜色

    我在 igraph 中使用 fastgreedy community 检测算法在 R 中生成社区 代码返回 12 个社区 但是在绘图时很难识别它们 因为它返回的图的颜色数量有限 我怎样才能用十二种不同的颜色绘制这个图表 l2 lt layo
  • 手动设置scale_fill_distiller()的比例

    我正在尝试制作一系列图表进行比较 举例来说 我想使用iris数据集来制作这样的图 其中我已过滤以仅查看 setosa 物种 library ggplot2 library dplyr iris gt filter Species setos
  • RStudio 如何确定控制台宽度,为什么它似乎总是出错?

    我刚刚发现wid lt options width在 RStudio 中 它似乎是我日常控制台使用中令人烦恼的根源 或者更确切地说 更接近根源 我应该先说一下 我目前使用的是 R 3 2 2 RStudio 0 99 491 Linux M

随机推荐