首页 > 编程问答 >点数据未渲染 - 散布地图框

点数据未渲染 - 散布地图框

时间:2024-07-30 12:01:59浏览次数:8  
标签:python plotly plotly-dash

我正在使用plotly 绘制一个散点图框。底图工作正常,但点未渲染。如果我打印图像,点就会出现。如果我还将 .show() 添加到图中,则会有一个单独的链接显示这些点。但我希望下拉栏选择单个状态和要可视化的点。我不知道我做错了什么?

import dash
from dash import Dash, dcc, html, Input, Output
import dash_bootstrap_components as dbc
import plotly.express as px
import pandas as pd
import plotly.graph_objs as go
import numpy as np

mapboxtoken = "xxx"


us_cities = pd.read_csv(
    'https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv'
)

stateID = us_cities['State'].unique()

external_stylesheets = [dbc.themes.SPACELAB, dbc.icons.BOOTSTRAP]

app = dash.Dash(__name__, external_stylesheets = external_stylesheets)

app.layout = html.Div([

    dcc.Dropdown(id="states_select",
             options=stateID,
             optionHeight=25,
             multi=True,
             searchable=True,
             placeholder='Please select...',
             clearable=True,
             value=[''],
             style={'width': "60%"}
             ),
             
    html.Div([
        dcc.Graph(id="the_graph")
   ]),

])

@app.callback(
    Output("the_graph", "figure"),
    Input("states_select", "value"),
)

def update_graph(states_chosen):

    dff = us_cities[us_cities["State"].isin(states_chosen)]

    scatter = px.scatter_mapbox(data_frame = dff, 
                               lat = 'lat', 
                               lon = 'lon',
                               zoom = 0,
                               hover_data = ['State', 'lat', 'lon']
                               )
    
    scatter.update_layout(
        height = 750,
        mapbox=dict(
        style='carto-positron',
        accesstoken=mapboxtoken,
        ),
        margin={'r':10, 't': 0, 'l': 0, 'b': 0}
    )

    #scatter.show()

    return scatter

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

代码中存在一个小错误导致了问题。 dcc.Graph 组件中缺少 figure 属性。你需要在 dcc.Graph 中初始化一个空白图形或默认图形,以便回调能够更新它。

以下是更新后的代码:

import dash
from dash import Dash, dcc, html, Input, Output
import dash_bootstrap_components as dbc
import plotly.express as px
import pandas as pd
import plotly.graph_objs as go
import numpy as np

mapboxtoken = "xxx"


us_cities = pd.read_csv(
    'https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv'
)

stateID = us_cities['State'].unique()

external_stylesheets = [dbc.themes.SPACELAB, dbc.icons.BOOTSTRAP]

app = dash.Dash(__name__, external_stylesheets = external_stylesheets)

app.layout = html.Div([

    dcc.Dropdown(id="states_select",
             options=stateID,
             optionHeight=25,
             multi=True,
             searchable=True,
             placeholder='Please select...',
             clearable=True,
             value=[''],
             style={'width': "60%"}
             ),

    html.Div([
        dcc.Graph(id="the_graph", figure={})  # <-- 添加 figure={}
   ]),

])

@app.callback(
    Output("the_graph", "figure"),
    Input("states_select", "value"),
)

def update_graph(states_chosen):

    dff = us_cities[us_cities["State"].isin(states_chosen)]

    scatter = px.scatter_mapbox(data_frame = dff, 
                               lat = 'lat', 
                               lon = 'lon',
                               zoom = 0,
                               hover_data = ['State', 'lat', 'lon']
                               )

    scatter.update_layout(
        height = 750,
        mapbox=dict(
        style='carto-positron',
        accesstoken=mapboxtoken,
        ),
        margin={'r':10, 't': 0, 'l': 0, 'b': 0}
    )

    return scatter

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

通过添加 figure={} , 你就在 dcc.Graph 组件中创建了一个空的图形对象,回调函数可以更新它并将数据显示在网页上。

标签:python,plotly,plotly-dash
From: 78809766

相关文章

  • 在家用电脑上设置 Python 和 Jupyter,尝试打开 Jupyter 笔记本并显示错误,无法获取
    我有最新的Python版本3.12.4和以下版本的Jupyter:SelectedJupytercorepackages...IPython:8.26.0ipykernel:6.29.5ipywidgets:notinstalledjupyter_client:8.6.2jupyter_core:5.7.2jupyter_server:2.14.2jupyterlab......
  • Python - Reloading a module
    Eachmoduleisloadedintomemoryonlyonceduringaninterpretersessionorduringaprogramrun,regardlessofthenumberoftimesitisimportedintoaprogram.Ifmultipleimportsoccur,themodule’scodewillnotbeexecutedagainandagain.Suppose......
  • vscode python 3.7 pylance debugpy 插件 vsix
    可能报错  crashed5timesinthelast3minutes.Theserverwillnotberestarted.  ---pylance 可能报错  cannotreadpropertiesofundefinedreadingresolveEnvironment   --- debugger可能      vscodepython3.7调试没有反应......
  • Python获取秒级时间戳与毫秒级时间戳的方法[通俗易懂]
    参考资料:https://cloud.tencent.com/developer/article/21581481、获取秒级时间戳与毫秒级时间戳、微秒级时间戳代码语言:javascript复制importtimeimportdatetimet=time.time()print(t)#原始时间数据print(int(t))......
  • CEFPython
    在Tkinter界面中直接嵌入Selenium的浏览器视图并不是一件直接的事情,因为Selenium本身并不提供图形界面嵌入的功能。Selenium主要用于自动化web浏览器,但它并不直接控制浏览器窗口的显示方式,而是依赖于WebDriver来与浏览器交互。然而,你可以使用一些替代方案来在Tkinter应用中模拟或......
  • 《最新出炉》系列初窥篇-Python+Playwright自动化测试-58 - 文件下载
    1.简介前边几篇文章讲解完如何上传文件,既然有上传,那么就可能会有下载文件。因此宏哥就接着讲解和分享一下:自动化测试下载文件。可能有的小伙伴或者童鞋们会觉得这不是很简单吗,还用你介绍和讲解啊,不说就是访问到下载页面,然后定位到要下载的文件的下载按钮后,点击按钮就可以了。其实......
  • Python - Function Annotations
     deffunc(s:str,i:int,j:int)->str:returns[i:j]Theparametersissupposedtobeastring,soweplaceacolonaftertheparameternameandthenwritestr.Parametersiandjaresupposedtobeintegerssowewriteintforthem.Returntypeis......
  • 使用带有 pythonKit XCODE 的嵌入式 Python,在 iOS 应用程序中与 OpenCV-python 签名不
    我根据Beewares使用指南在XCODE中将Python嵌入到我的iOS项目中https://github.com/beeware/Python-Apple-support/blob/main/USAGE.md运行时,我得到pythonKit找不到由ultralytics导入的cv2错误。当我将OpenCV-python添加到我的app_packages文件夹时......
  • Python - Arguments and Parameters
    ParametersinFunctionDefinitionA.deffunc(name):MatchbypositionorbynameB.deffunc(name=value):DefaultargumentC.deffunc(*args):CollectextrapositionalargumentsintuplenamedargsD.deffunc(**kwargs):Collectextrakeywordargumentsi......
  • Python MySQL 无法连接,原因不明
    当我尝试使用python连接到我的MySQL数据库时,由于未知原因显示错误:dTraceback(mostrecentcalllast):File"/usr/local/bin/flask",line8,in<module>sys.exit(main())^^^^^^File"/usr/local/lib/python3.12/site-packages/flask/cli.py&......