带有Choroplethmapbox的地图未显示在仪表板中

2024-10-04 03:19:45 发布

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

我正试图用破折号中的Choroplethmapbox构建一个地图,但我无法用它进行绘图

我使用另一个工具测试geojson,在该工具中,地图绘制正确,但不使用Choroplethmapbox

你知道我做错了什么吗

谢谢

GeoJson:

https://gist.github.com/Tlaloc-Es/5c82834e5e4a9019a91123cb11f598c0

Python破折号代码:

import json
with open('mexico.geojson') as f:
    counties = json.load(f)
fig = go.Figure(go.Choroplethmapbox(
    geojson=counties,
    locations=df['COV_'],
    z=df['Enero'],
    colorscale="Viridis", zmin=0, zmax=df['Enero'].max(),
    marker_opacity=0.5, marker_line_width=0))

fig.update_layout(mapbox_style="carto-positron",
                  mapbox_zoom=3, mapbox_center = {"lat": 37.0902, "lon": -95.7129})
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})

Tags: 工具jsongodfgeojson地图figupdate
3条回答

我需要添加一个带有此代码的id:

我使用了这个页面的代码:https://community.plot.ly/t/plot-a-shapefile-shp-in-a-choropleth-chart/27850

看起来您缺少底部的fig.show(),而顶部的导入plotly.graph\u对象为go。下面的代码将打开一个映射,但choropleth值需要数据。您的代码示例中有df,但没有包含csv。如果您想使用代码中的df,请导入pandas,并从csv创建一个名为df的数据帧。这里有一个链接可以帮助您实现这一点Pandas dataframes

import json
import plotly.graph_objects as go


with open(r'{insert file path here}.geojson') as f:
    counties = json.load(f)
fig = go.Figure(go.Choroplethmapbox(
    geojson=counties,
    colorscale="Viridis", zmin=0, zmax=100,
    marker_opacity=0.5, marker_line_width=0))

fig.update_layout(mapbox_style="carto-positron",
                  mapbox_zoom=3, mapbox_center = {"lat": 37.0902, "lon": -95.7129})
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

下面是一个在json中使用pandas的示例。下面代码的进一步解释可以在here

from urllib.request import urlopen
import json
with urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:
    counties = json.load(response)

import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv",
                   dtype={"fips": str})

import plotly.express as px

fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',
                           color_continuous_scale="Viridis",
                           range_color=(0, 12),
                           scope="usa",
                           labels={'unemp':'unemployment rate'}
                          )
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

我必须解决一个类似的问题,这是我应用于您的问题的解决方案(尽管使用了px.choropleth_mapbox而不是我发现对choropleths来说很混乱的graph_对象)

  • 您链接的数据没有(至少在编写本文时没有)列“Enero”
  • 你从来没有定义过Dash应用程序(app.layout = ...),而你可能不用它就可以服务,只需按照建议使用fig.show(),显式优于隐式。因此,创建布局部分更好
  • 如果我理解它是如何工作的,如果您使用GeoPandas,就不必像您在自己的答案中建议的那样生成“id”或类似的内容

不管怎样,希望我的解决方案可以作为你工作的开始。我添加了单选按钮,以便您可以选择要用于颜色的数据列

import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.express as px

import geopandas as gpd

print('Loading data...')
gdf = gpd.read_file('https://gist.githubusercontent.com/Tlaloc-Es/5c82834e5e4a9019a91123cb11f598c0/raw/709ce9126861ef7a7c7cc4afd6216a6750d4bbe1/mexico.geojson')
gdf = gdf.to_crs(epsg=4326)

print('Done!')
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    html.Div([
                dcc.RadioItems(
                    id='radio-color_on',
                    options=[{'label': i, 'value': i} for i in ['AREA','PERIMETER']],
                    value='AREA',
                    labelStyle={'display': 'inline-block'}
                ),
    ],style={'width': '40%', 'display': 'inline-block',}),

html.Div([], style={'width':'100%'}),

    html.Div([
                dcc.Graph(id="fig")
    ],style={'width': '100%', 'display': 'inline-block', 'padding': '0 10',},),
]) 

@app.callback(
    Output("fig", "figure"), 
    [Input("radio-color_on", "value")])
def draw_choropleth(color_on):
    fig = px.choropleth_mapbox(gdf, 
                            geojson=gdf.geometry, 
                            locations=gdf.index, 
                            color=color_on,
                            color_continuous_scale="Viridis",
                            #range_color=(0, 12),
                            mapbox_style="carto-positron",
                            zoom=4, 
                            center = {"lat":gdf.centroid.y.mean(), "lon":gdf.centroid.x.mean()},
                            opacity=0.5,
                            )
    fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0},
                        height=700,
                        )
    
    return fig

if __name__ == '__main__':
    app.run_server(debug=True)

将此代码保存到文件“myapp.py”中,并在终端中以python myapp.py的形式运行它,启动web浏览器,导航到它所使用的url(它在终端中写出,通常为172.0.0.1:8050),这样您可以:

enter image description here

我从默认的anaconda频道运行这些版本

  • 破折号1.19.0
  • 仪表板核心部件1.3.1
  • 破折号html组件1.0.1
  • 仪表板渲染器1.1.2
  • 烧瓶1.1.2
  • geopandas 0.8.1

顺便说一句,我实际上是用这些数据问了一个关于dash choropleth映射框选择行为(Selection behavior in plotly-dash Choropleth mapbox plot)的问题。谢谢

相关问题 更多 >