complete Solution:
from shapely.geometry import Polygon
import geopandas as gpd
import numpy as np
import json
import plotly.express as px
def generateColorScale(colors, naColor):
colorArray=[]
colorArray.append([0,naColor])
for grenze, color in zip(np.linspace(0.01,1,len(colors)), colors):
colorArray.append([grenze, color])
return colorArray
geometry = gpd.GeoSeries([Polygon([(0, 0), (1, 0), (1, 1), (0, 1)]), Polygon([(1, 1), (2, 1), (2, 2), (1, 2)]), Polygon([(1, 0), (2, 0), (2, 1), (1, 1)]), Polygon([(0, 1), (1, 1), (1, 2), (0, 2)])])
geoDf = gpd.GeoDataFrame(data={"Name":["a","b","c","d"], "geometry": geometry}, geometry="geometry")
dataDf = pd.DataFrame(data={"Data":[1.0,1.5,2,np.nan]}).fillna(-1)
fig = px.choropleth_mapbox(dataDf,
geojson=geoDf.geometry,
locations=dataDf.index,
color="Data",
title="Data",
mapbox_style="white-bg",
center = {"lat": 1, "lon": 1},
zoom=6,
color_continuous_scale=generateColorScale(colors=["white","red"], naColor="gray"),
range_color=(np.unique(dataDf["Data"])[1]*0.99, np.max(dataDf["Data"])),
hover_name="Data",
)
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
fig.show()
I got inspired by this redirecting to this post.
- you need to change the minimum of
range_color
, else your lowest value is in the naColor as well - fill the missing values with a value lower then all values in the Data
hope that does help some other plotly users