Plotly.express choropleth仅显示一种颜色

时间:2020-07-03 16:50:02

标签: python pandas plotly choropleth

我正在尝试使用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参数来指定the docs中所写的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

我的geojson和csv可以下载here

1 个答案:

答案 0 :(得分:2)

在绘制之前必须先解开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/2619 Solved