choropleth plotly with shapefiles not working

72 Views Asked by At

I'm downloading Fema's shapefiles (https://hazards.fema.gov/nri/data-resources) because I want to add a layer of my own data on top of it.

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

How come this doesn't work?

1

There are 1 best solutions below

1
On

I think that if you are trying to access variables from the geojson, then the variables need to be quoted. I couldn't get this to work with the hover text yet so I left that out of the code for now.

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

You can also access the variables from the shapefile (that was imported as a list) using the $ operator. In this case you want to get variables form counties, not from counties_geo. See below:

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