Plotly Choropleth地图无法填充数据问题求助
Here are the most common fixes for your blank map issue:
Ensure state abbreviations are uppercase: Plotly's
locationmode='USA-states'strictly requires uppercase 2-letter state codes (e.g., 'CA', 'TX'). Mixed or lowercase codes won't be recognized. Fix this with:df['state'] = df['state'].str.upper()Validate state codes for errors: Check for missing values, typos, or non-standard abbreviations (like 'NYC' instead of 'NY'). Use this to inspect unique state values:
print(df['state'].unique())Filter out any invalid entries before plotting.
Double-check parameter mappings: Confirm your
px.choroplethcall correctly maps columns to parameters:fig = px.choropleth( df, locations='state', # Must match your state column name exactly locationmode='USA-states', color='Users', # Must match your user count column name scope='usa' )Verify non-zero user counts: If all values in the
Userscolumn are zero, the map will appear blank (no color variation). Check with:print(df['Users'].describe())Update Plotly: Older versions of Plotly might have bugs with US state choropleths. Update to the latest version:
pip install --upgrade plotly
Example Corrected Code
import plotly.express as px import pandas as pd # Load data df = pd.read_csv('your_data.csv') # Clean state codes df['state'] = df['state'].str.upper() df = df[df['state'].str.len() == 2] # Filter out invalid codes # Create map fig = px.choropleth( df, locations='state', locationmode='USA-states', color='Users', scope='usa', title='US State User Counts' ) fig.show()
内容的提问来源于stack exchange,提问作者Alex

