首页 > 解决方案 > 使用 plotly 在 R 上创建交互式地图

问题描述

我正在尝试创建从 ggplot2 到 plotly 的动态地图。

我尝试了以下方法:

library(geobr)
library(dplyr)
library(ggplot2)
library(sf)
library(ggthemes)


# download sf of Brazilian states
states <- read_state(code_state = 'all')

map <- ggplot() +
  geom_sf(data=states, color="gray90", fill="gray80", size=.4) +
  theme_map() +
  theme( strip.background = element_rect(colour = "white", fill = "white"),
         strip.text.x = element_text(size = 8, face ="bold"))

地图

如何将此地图转换为交互式地图?我正在尝试遵循此示例(链接

使用情节,我无法得到:

library(plotly)
ggplotly(map)

Error in st_coordinates.sfc(sf::st_geometry(model)) : 
  not implemented for objects of class sfc_GEOMETRY

标签: rdictionaryggplot2plotly

解决方案


解决方案是使用函数 sf::st_cast('your geobr map dataset', "MULTIPOLYGON")。

library(plotly)
library(ggplot2)
library(sf)
library(geobr)
library(ggthemes)

states <- read_state(code_state = 'all')
states = sf::st_cast(states, "MULTIPOLYGON")

map <- ggplot() +
  geom_sf(data=states, color="gray90", fill="gray80", size=.4) + 
  theme_map() +
  theme( strip.background = element_rect(colour = "white", fill = "white"),
         strip.text.x = element_text(size = 8, face ="bold"))

ggplotly(map)

请参阅此处的讨论:https ://github.com/ipeaGIT/geobr/issues/172


推荐阅读