Search code examples
rplotlyr-plotlychoropleth

r plotly combined bubble and choropleth map using lat lon instead of fips code


I have a dataset with columns "state_name", "county_name", "value1", "value2", "lat", and "lon". I've tried to apply the examples from the Plotly website and other resources with my data but I'm not getting any luck. They only seem to have an example with the fipscode, and I'm not sure how to use "lat" and "lon" information on my code.

This is the example code I found from the plotly website. Is there a way to plot the map with only the "lat" and "lon" information without having to use counties JSON and the fips code?

library(rjson)
library(plotly)

url <- 'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json'
counties <- rjson::fromJSON(file=url)
url2<- "https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv"
df <- read.csv(url2, colClasses=c(fips="character"))
fig <- plot_ly() 
fig <- fig %>% add_trace(
    type="choroplethmapbox",
    geojson=counties,
    locations=df$fips,
    z=df$unemp,
    colorscale="Viridis",
    zmin=0,
    zmax=12,
    marker=list(line=list(
      width=0),
      opacity=0.5
    )
  )
fig <- fig %>% layout(
    mapbox=list(
      style="carto-positron",
      zoom =2,
      center=list(lon= -95.71, lat=37.09))
  )
fig


Solution

  • Given the example you provided, I assume you want to color the counties by either value1 or value2. In this case, you believe you need the geojson as these draw the county's boundaries so that the color gradient can be applied. Depending on what you are looking for:

    • If you are looking for the fill counties style (strictly choropleth map), you can potentially convert the fips code from the state_name and county_name using this dataset (Counties and FIPS Dataset); you can merge by the county and state to obtain the FIPS codes.
    • If you are not looking for a choropleth map, you might not need the geojson object; a bubble map might be more suitable (Plotly bubble Maps) as you only need the lat and long to plot this.