Reputation: 191
I have a Pandas dataframe df
that looks as follows:
user_id zip_code city county state
0001 10021 New York New York NY
0002 10003 New York New York NY
0003 06831 Greenwich Fairfield CT
0004 33172 Miami Miami-Dade FL
0005 07417 Franklin Lakes Bergen NJ
I'm trying to plot a zip-code level choropleth using the following:
from urllib.request import urlopen
import json
import requests
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
counties = json.load(response)
fig = px.choropleth(df,
geojson= counties,
locations='fips',
locationmode="USA-states",
scope="usa",
color='user_id',
color_continuous_scale="blues",
)
fig.show()
But, the map is rendering as blank.
How do I render a zip-code level choropleth?
Upvotes: 1
Views: 4849
Reputation: 35135
The reason it is not displayed is because the geojson file you are using does not have the zip code data. Therefore, it is necessary to prepare a geojson file with zip codes. As an example, I created a graph with sample data from here. Depending on your data, if you want to handle zip codes for the entire US, the number of data will be huge and will affect the performance.
from urllib.request import urlopen
import json
import requests
# Nevada Zip code
url = 'https://raw.githubusercontent.com/OpenDataDE/State-zip-code-GeoJSON/master/nv_nevada_zip_codes_geo.min.json'
with urlopen(url) as response:
nv_zip_json = json.load(response)
zip_code = []
for i in range(len(nv_zip_json['features'])):
code = nv_zip_json['features'][i]['properties']['ZCTA5CE10']
zip_code.append(code)
import pandas as pd
import numpy as np
df = pd.DataFrame({'zip_code': zip_code, 'value': np.random.randint(0,30, len(nv_zip_json['features']))})
df['zip_code'] = df['zip_code'].astype(str)
import plotly.express as px
fig = px.choropleth(df,
geojson= nv_zip_json,
locations='zip_code',
featureidkey="properties.ZCTA5CE10",
color='value',
color_continuous_scale="blues",
projection="mercator",
)
fig.update_geos(fitbounds="locations", visible=False)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()
To draw a map by county using the current data, the following code can be used.
import plotly.express as px
fig = px.choropleth(df,
geojson= counties,
locations='county',
featureidkey="properties.NAME",
scope="usa",
color='user_id',
color_continuous_scale="blues",
)
fig.show()
Upvotes: 4