我正在下载 FEMA 的 shapefile (https://hazards.fema.gov/nri/data-resources),因为我想在其上添加一层我自己的数据。
library(sf);library(dplyr);library(plotly)
counties=st_read(dsn="~/Climate Change/NRI_Shapefile_Counties/NRI_Shapefile_Counties.shp")
counties_geo=sf_geojson(counties)
fig <- plot_ly()
fig <- fig %>% add_trace(
type="choropleth",
geojson=counties_geo,
locations=counties_geo$COUNTYFIPS,
z=counties_geo$RISK_SCORE,
showscale=T,
text = ~paste(counties_geo$COUNTY, "<br>Risk Rating:", counties_geo$RISK_RATNG), # Hover text
hoverinfo = "text",
marker=list(line=list(width=0))
)
fig
这怎么行不通?
我认为如果您尝试从 geojson 访问变量,那么需要引用这些变量。我还无法让它与悬停文本一起使用,所以我暂时将其排除在代码之外。
library(sf);library(dplyr);library(plotly);library(geojsonsf);
counties_geo=sf_geojson(counties)
fig <- plot_ly()
fig <- fig %>% add_trace(
type="choropleth",
geojson=counties_geo,
locations="COUNTYFIPS",
z="RISK_SCORE",
showscale=T,
hoverinfo = "text",
marker=list(line=list(width=0))
)
fig
您还可以使用
$
运算符从 shapefile(作为列表导入)访问变量。在这种情况下,您希望从 counties
获取变量,而不是从 counties_geo
获取变量。见下图:fig <- plot_ly()
fig <- fig %>% add_trace(
type="choropleth",
geojson=counties_geo,
locations=counties$COUNTYFIPS,
z=counties$RISK_SCORE,
showscale=T,
hoverinfo = "text",
marker=list(line=list(width=0))
)
fig