我正在使用
plotly
创建一个带有颜色编码和动画点的地图以及一个 sf
对象。这些点本身就很好绘制。 sf
对象也可以很好地绘制。当我尝试使用 sf
选项将动画颜色编码与 inherit = FALSE
对象组合时,背景图不再绘制。我究竟做错了什么?任何帮助将不胜感激!
玩具示例:
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, 0.5)) %>%
mutate(Group = sample(c("a", "b"), n(), replace = TRUE))
# plots points correctly, the animation works
plot_ly(df, lat = ~y, lon = ~x, color = ~Group, frame = ~Group,
type = "scattermapbox", mode = 'markers') %>%
layout(mapbox= list(style ="stamen-terrain", zoom = 4,
center = list(lon = -80 ,lat= 35)))
# color-coding and animation work, and the sf object shows, but the map is gone
plot_ly() %>%
add_markers(data = df, y = ~y, x = ~x, color = ~Group, frame = ~Group,
type = "scattermapbox", mode = 'markers') %>%
add_sf(data = nc, x = ~x, y = ~y, inherit = FALSE) %>%
layout(mapbox= list(style ="stamen-terrain", zoom = 4,
center = list(lon = -80 ,lat= 35)))
您可以将 df 转换为 sf 对象并使用 sf 对象的 CRS。在plot_ly调用中,您不必定义经/纬度或x/y坐标,因为坐标取自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")
head(nc)
# check crs
st_crs(nc)
df <- expand.grid(x = seq(-76, -84, -2), y = seq(34, 36, 0.5)) %>%
mutate(Group = sample(c("a", "b"), n(), replace = TRUE))
# convert df to sf object and set crs
df <- st_as_sf(df, coords = c("x", "y"), crs = 4267)
head(df)
# color-coding and animation work, and the sf object shows, but the map is gone -> now it works
plot_ly() %>%
add_sf(data = df,
color = ~Group,
frame = ~Group,
type = "scattermapbox",
mode = 'markers') %>%
add_sf(data = nc,
type = "scattermapbox",
mode = 'lines',
inherit = FALSE) %>%
layout(mapbox= list(style ="open-street-map",
zoom = 4,
center = list(lon = -80 ,lat= 35)))
plot_ly