Home > Blockchain >  why the plotly map is empty?
why the plotly map is empty?

Time:10-22

What am I doing wrong that this code returns the partially empty map like this? ideally to have locations = 'zip' column instead of fips my map:(

import pandas as pd
import plotly.express as px
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:counties = json.load(response)

df = pd.read_csv('uszips.csv', dtype={'fips': str}) 

fig = px.choropleth(df,
                   geojson=counties, 
                   locations='fips', 
                   color='9/30/2022',
                   range_color=(50000, 1000000),
                   scope="usa")
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

CodePudding user response:

Find a US map, I found that Mesa County in Co state is not shown, and check its fips in uszips.csv, is 8077:

df1 = df[df["State"]=="CO"]
df1["Mesa" == df["City"]]

RegionID    SizeRank    zip fips    StateName   State   City    Metro   CountyName  9/30/2022
25162   93837   27031   71853   8077    CO  CO  Mesa    Grand Junction, CO  Mesa County 483912.0

open the https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json, search the Mesa, found the id is '08077'

  {'type': 'Feature',
   'properties': {'GEO_ID': '0500000US08077',
    'STATE': '08',
    'COUNTY': '077',
    'NAME': 'Mesa',
    'LSAD': 'County',
    'CENSUSAREA': 3328.974},
   'geometry': {'type': 'Polygon',
    'coordinates': [[[-109.059962, 38.499987],
    ....
      [-109.059962, 38.499987]]]},
   'id': '08077'},

so I modified the fips to 08077 of Mesa in uszips.csv, run again, then Mesa appeared: enter image description here

so the solution is:

import pandas as pd
import plotly.express as px
from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
    counties = json.load(response)

df = pd.read_csv('uszips.csv', dtype={'fips': str}) 
df["fips"] = df["fips"].map(lambda x: f"0{x}" if len(str(x))==4 else x)
fig = px.choropleth(df,
                   geojson=counties, 
                   locations='fips', 
                   color='9/30/2022',
                   range_color=(1, 40000000),
                   scope="usa")
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

there are still some blank area, find out the reason by yourself! enter image description here

  • Related