Plotly.express choropleth仅显示一种颜色

2024-04-25 00:20:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用plotly.express创建一个choropleth。图形可以加载,但它只显示一种颜色。我可以将鼠标移到每个功能上,它会显示相关信息,但不会以可变颜色显示。这意味着它正在读取geojson,但没有正确显示u/geds133 had the same issue,但我无法与他们联系或发表评论,因为声誉很低

以下是我的“预测”df:

import pandas as pd
predictions = pd.read_csv("Predictions_DF_2002.csv")

predictions.head()

huc12           Predicted PRBT   Std
170102120304    30.677075        23.348831
170102120603    31.362211        23.784001
90400010201     5.697461         7.688427
100301040401    3.493039         5.36472
170101011208    4.421055         11.924093

我正在尝试将DataFrame与geojson文件中的属性匹配:

#Read in geojson
import geopandas as gpd
import json


hucs = gpd.read_file(~/"HUC.geojson")

#Populate hucs['properties'] (i.e. convert to plotly-readible geojson-type)
hucs = json.loads(hucs.to_json())

#Print Properties for sanity check
print(hucs['features'][0]['properties'])
#...<a bunch of stuff we don't care about> 
{'huc12':170102120304}
#...

因此,我可以使用featureidkey参数指定在哪里匹配locations中写入的值。下面是我用来创建choropleth的代码:

fig = px.choropleth(predictions,
                    geojson=hucs, color='Predicted PRBT',
                    locations='huc12', featureidkey='properties.huc12',
                    color_continuous_scale="Viridis", labels={'Predicted PRBT':'Predicted % RBT'})
fig.update_geos(fitbounds="locations",visible=False)
fig.show()

下面是输出显示的内容。请注意,鼠标悬停显示相关信息: Choropleth Output

My geojson和csv可供下载here


Tags: csvimportjson颜色geojsonfigpropertiesplotly
1条回答
网友
1楼 · 发布于 2024-04-25 00:20:01

在打印之前,必须解开geojson:

#Read in geojson
import geopandas as gpd
import json


hucs = gpd.read_file(~/"HUC.geojson")

#Populate hucs['properties'] (i.e. convert to plotly-readible geojson-type)
hucs = json.loads(hucs.to_json())

from geojson_rewind import rewind
hucs_rewound = rewind(hucs,rfc7946=False)


fig = px.choropleth(predictions,
                    geojson=hucs_rewound, color='Predicted PRBT',
                    locations='huc12', featureidkey='properties.huc12',
                    color_continuous_scale="Viridis", labels={'Predicted PRBT':'Predicted % RBT'})
fig.update_geos(fitbounds="locations",visible=False)
fig.show()

https://github.com/plotly/plotly.py/issues/2354#issuecomment-638742767https://github.com/plotly/plotly.py/issues/2619Solved

相关问题 更多 >