使用plotly.express绘制Choropleth Map仅显示图例,地图及交互控件异常求助
Hey there! Let's work through this choropleth map issue together— I’ve dealt with similar headaches before, so here are actionable fixes you can try right away:
Verify Your GeoJSON Data Integrity
First up, make sure your GeoJSON is valid and properly structured. You can use Python'sgeojsonlibrary to validate it locally. Double-check that the property key you’re using to index (like'id'or a district name) matches exactly between your GeoJSON'spropertiesfield and your DataFrame column— even a tiny typo (capitalization, extra spaces) will break the map rendering. If your GeoJSON is huge, try trimming it down to just a few features to rule out loading issues from oversized data.Check Your Plotly Rendering Environment
If you’re running this in a Jupyter Notebook, the built-in renderer can sometimes act up. Try switching to browser rendering by adding this line beforefig.show():import plotly.io as pio pio.renderers.default = 'browser'For standalone scripts, ensure
fig.show()is actually executing and isn’t blocked by other code (like an unclosed file handle or infinite loop).Audit Your Choropleth Parameter Setup
- Confirm you’re passing the parsed GeoJSON dictionary to the
geojsonparameter, not just a file path. If you’re loading from a file, usejson.load(open('your_geo_file.geojson'))to read it into a Python dict first. - Match
locationmodeto your indexing method: if you’re using a property from the GeoJSON, setlocationmode='geojson-properties'and ensurelocationspoints to the corresponding DataFrame column, whilefeatureidkeymatches the exact property name in your GeoJSON (e.g.,featureidkey="properties.district"). - Make sure your
zparameter (the numerical column driving the color scale) has no missing or invalid values (like NaNs)— empty values can prevent the map from rendering even if the legend shows up.
- Confirm you’re passing the parsed GeoJSON dictionary to the
Update Dependencies Beyond Plotly
Even with the latest Plotly, outdated dependencies likepandas,numpy, orgeojsoncan cause compatibility glitches. Run these commands to refresh them:pip install --upgrade numpy pandas geojsonTest with a Minimal Working Example
Rule out code-specific issues by running Plotly’s official minimal choropleth example first:import plotly.express as px df = px.data.election() geojson = px.data.election_geojson() fig = px.choropleth(df, geojson=geojson, color="Bergeron", locations="district", featureidkey="properties.district", projection="mercator") fig.update_geos(fitbounds="locations", visible=False) fig.show()If this works perfectly, the problem lies in your custom data/GeoJSON pairing. Start swapping in your data piece by piece to pinpoint where the mismatch happens.
内容的提问来源于stack exchange,提问作者Almog Woldenberg

