带有 shapefile 的分区统计图不起作用

choropleth plotly with shapefiles not working

提问人:Ashti 提问时间:11/1/2023 更新时间:11/1/2023 访问量:38

问:

我正在下载 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

为什么这不起作用?

r 绘图 等值统计

评论

0赞 gregor-fausto 11/1/2023
您能澄清一下您共享的代码的哪一部分不适合您吗?您是否在下载 shapefile 或打印它们时遇到问题?还是其他问题?
0赞 Ashti 11/1/2023
我无法绘制它们,并将它们转换为geojson格式以帮助绘制它们
0赞 gregor-fausto 11/1/2023
在您链接到的 FEMA 页面上,您正在下载哪些文件,然后尝试绘制?我在页面上看到了 5 个国家风险指数的 shapefile。
0赞 Ashti 11/1/2023
我正在下载这个:hazards.fema.gov/nri/Content/StaticDocuments/DataDownload//...并将其解压缩到我的文件夹位置并使用 .shp 文件

答:

0赞 gregor-fausto 11/1/2023 #1

我认为,如果您尝试从 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(以列表形式导入)访问变量。在这种情况下,您希望从 形式获取变量,而不是从 .见下文:$countiescounties_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

评论

0赞 Ashti 11/1/2023
这不起作用,当我运行它时它会显示一个灰色屏幕