Automatically set outline and fill color based on GeoJSON properties with geopandas

Question:

I am making a program that retrieves GeoJSON data from past convective outlooks from the Storm Prediction Center (SPC) and plot it using geopandas. With my current code, it is able to plot outlooks correctly onto a map. However, the coloring isn’t right. I noticed that the GeoJSON returned by the SPC included outline and fill coloring data for the categories – (in properties field)

{"type": "FeatureCollection", "features": [{"type": "Feature", "geometry": {"type": "MultiPolygon", "coordinates": ...}, "properties": {"DN": 2, "VALID": "202109010100", "EXPIRE": "202109011200", "ISSUE": "202109010042", "LABEL": "TSTM", "LABEL2": "General Thunderstorms Risk", "stroke": "#55BB55", "fill": "#C1E9C1"}}, {"type": "Feature", "geometry": {"type": "MultiPolygon", "coordinates": ...}, "properties": {"DN": 3, "VALID": "202109010100", "EXPIRE": "202109011200", "ISSUE": "202109010042", "LABEL": "MRGL", "LABEL2": "Marginal Risk", "stroke": "#005500", "fill": "#66A366"}}, {"type": "Feature", "geometry": {"type": "MultiPolygon", "coordinates": ...}, "properties": {"DN": 4, "VALID": "202109010100", "EXPIRE": "202109011200", "ISSUE": "202109010042", "LABEL": "SLGT", "LABEL2": "Slight Risk", "stroke": "#DDAA00", "fill": "#FFE066"}}]} 

Is it possible to use the stroke and fill data in properties to automatically color every MultiPolygon?

My current code is below (assume that all packages are imported)

outlook = "https://www.spc.noaa.gov/products/outlook/archive/2021/day1otlk_20210901_0100_cat.lyr.geojson"
world = geopandas.read_file(
    geopandas.datasets.get_path('naturalearth_lowres')
)
df = geopandas.read_file(outlook)
ax = world.plot(color='white', edgecolor='#333333',linewidth=0.3)
print(type(df))
s = geopandas.GeoDataFrame(df)
s.plot(ax=ax,markersize=0.7,figsize=(1000,1000))
ax.set_xlim(-140, -70) # focus on continental US
ax.set_ylim(25, 50) # focus on continental US
plt.savefig('outlook.jpg', dpi=360) # save as outlook.jpg

I tried looking in the geopandas documentation but it didn’t state how to use fields in geojson to color polygons.

Asked By: Jellyfish

||

Answers:

You’re one kwarg away from the final result. plot accepts Series as an argument for color :

colorstr, np.array, pd.Series (def: None) If specified, all objects
will be colored uniformly.

s.plot(ax=ax, color=s["fill"], markersize=0.7, figsize=(1000,1000)) # <-  color=s["fill"] (added here)

Output :

enter image description here

Answered By: Timeless