Search code examples
rshinyplotlyr-plotly

Plotly map missing states in Shinny web application


I am trying to create an interactive plot with Plotly in Shinny that shows all American counties color-coded by population. However, the state of California, Alabama, Arizona, Colorado, and Arkansas are missing when I run the following code as a part of the server.R function:

output$countyPolygonMap <- renderPlotly({
        url <- 'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json'
        countyGeo <- rjson::fromJSON(file=url)
        ## Obtaining the geographical file for all U.S. counties
        url2<- "https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv"
        df <- read.csv(url2, colClasses=c(fips="character"))
        names(df)[2] = "unemployment"
        ## obtaining the unemployment rate data 
        url3 <- "https://storage.googleapis.com/kagglesdsdata/datasets%2F579969%2F1374720%2Fus_county.csv?GoogleAccessId=gcp-kaggle-com@kaggle-161607.iam.gserviceaccount.com&Expires=1596139521&Signature=easqHBFZ757D%2F7LVyDM%2BF%2FIMU6l2OEY6giqVvIC0l0tSSe%2Fohq6NC%2FLFKbsIV6FdFALmPUqG9vATbg0cuRVVwGQMsoUOjlW%2BZLhTVluxbYh1dDE1MTFzWRpzlSH18ejIwqa61F0ARJ%2Bpq6ryIfJuE7wQQ1rOCEpaVB9m%2FP7QaZm2gBJeHYLXJXcvO8w1p0sEnqRsGAesg2Fgj%2Bv8unPGNtDJekEWuNbl1K9k7CAaZWjG2QQ94LB9tAPvfKqykDWDD7w6yN3YFkcfu7kUmjs0CybnMD6IP%2FM5hvJXuUTIie0MOMTWt5bIua4qcTHxIxR5l918y1H17JA2HHrnKLVY%2BA%3D%3D"
        county <- read.csv(url3)

        countyPolygonMap <- plot_ly() %>% add_trace(
            type="choroplethmapbox",
            geojson=countyGeo,
            locations=county$fips,
            z=~county$population,
            colorscale="Viridis",
            zmin=0,
            zmax=12,
            marker=list(line=list(width=0),opacity=0.5)
        ) %>% layout(
            mapbox=list(
                style="carto-positron",
                zoom =2,
                center=list(lon= -95.71, lat=37.09))
        );
        countyPolygonMap;
        ## generating the interactive plotly map
    })

I double-checked with the source data and there is no problem or NA. R is not getting any warning or error either. Can you help me with it?


Solution

  • fips needs to be 5 digits. You can convert it as county$nfips <- sprintf("%05d",county$fips). Then use nfips in your plotly and you get the following output:

    output

    Please note that you were missing Alaska and Connecticut also - all with 4-digit fips.