简体   繁体   中英

Plot single state choropleth map in plotly/how to index geojson

I am using geojson data and would like to plot a choropleth map of a single state. To do this, I would need to extract individual states from my geojson data. Here is the geojson data from plotly's Github I'm using (county level):

import plotly.express as px
import requests
import json

r = requests.get(
    'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json'
    )
counties = json.loads(r.text)

I have written the following code to extract all counties of Alabama:

target_states = ["01"]
al = [i for i in counties["features"] if i["properties"]["STATE"] in target_states]

This, however, breaks the structure of the json (I think) as it is now just a list of the county dictionaries. When I tried to use al to plot a choropleth map it did not work (it compiled but showed a completely blank plot). However, when I tried to index this list with al[0] , the individual county I indexed was plotted correctly. I figured I could add all of the dictionaries within the list together with the following:

new = {}
for i in al:
  new.update(i)

But it didn't work as I expected and only one county was in new . However, if I run the following, all county dictionaries are printed

for i in al:
  print(i)

So, what I am trying to do is simply plot one inividual state by indexing them through the geojson data. I can index all counties from one state and can correctly plot individual counties, but I am stuck on the final step of plotting all counties of an individual state together to make up a single state plot.

What you're trying to do is filter your data according to a specific property without changing the structure. If you take a look at your counties object, it's a dictionary with this structure:

{
  'features': [
    {'geometry': .. , 'id': .. , 'properties': .. , 'type': ..},
    {'geometry': .. , 'id': .. , 'properties': .. , 'type': ..},
    ..
  ]
  'type': 'FeatureCollection'
}

To achieve this, discard any inner dictionary in the list of 'features' whose ['properties']['STATE'] is not in your target states. The easiest way to filter a list is with a list comprehension . To maintain the structure, simply filter counties['features'] and reassign the result to it:

target_states = ['01']
counties['features'] = [f for f in counties['features'] if f['properties']['STATE'] in target_states]

Here is the full code with a working example with the same example from plotly you probably used:

import plotly.express as px
import requests
import json
import pandas as pd

r = requests.get('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json')
counties = json.loads(r.text)
target_states = ['01']
counties['features'] = [f for f in counties['features'] if f['properties']['STATE'] in target_states]

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv', dtype={'fips': str})

fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',
                    color_continuous_scale='Viridis',
                    range_color=(0, 12),
                    scope='usa',
                    labels={'unemp': 'unemployment rate'}
                    )
fig.update_layout(margin={'r': 0, 't': 0, 'l': 0, 'b': 0})
fig.show()

Output:

在浏览器中绘制图形

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM