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.
CodePudding user response:
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 
