python - Choropleth Plotly Graph 未出现在 Dash 上
问题描述
我有一个包含各种状态的 csv 文件,以及它们在某些特定日期的分数。它在 VSCode Notebook 中正确绘制,但是当我尝试在 Dash 上显示它时,会出现默认地图,但没有颜色编码。我已经尝试更改数据集甚至显示选项,但它仍然是一样的。还有其他人面临这个吗?
我在下面附上我的整个 Dash 代码以供参考
#importing libraries
import dash
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
import pandas as pd
app = Dash(__name__)
#-- Import and clean data (importing csv into pandas)
df = pd.read_csv("C:\Data Science\Jupyter_Workspace\Twitter_Sentiment\Data\JSONLs\\final_df.csv")
#print(df[:5]) #printing out a sample to verify if it's correct or not
# Importing the GeoJSON File
import geojson
with open("C:\Data Science\Jupyter_Workspace\Twitter_Sentiment\Dash Deployment\states_india.geojson") as f:
india_states = geojson.load(f)
# ------------------------------------------------------------------------------
# App layout
app.layout = html.Div([
html.H1("Sentiment Timeline for Covid-19 in India 2021-22", style={'text-align': 'center'}),
dcc.Dropdown(id="selected_date",
options=[
{"label": "March 20, 2020", "value": 20200320},
{"label": "March 25, 2020", "value": 20200325},
{"label": "March 27, 2020", "value": 20200327},
{"label": "March 30, 2020", "value": 20200330}],
multi=False,
value=20200320,
style={'width': "40%"}
),
html.Div(id='output_container', children=[]),
html.Br(),
dcc.Graph(id='sentiment_map', figure={})
])
# ------------------------------------------------------------------------------
# Connect the Plotly graphs with Dash Components
@app.callback(
[Output(component_id='output_container', component_property='children'),
Output(component_id='sentiment_map', component_property='figure')],
[Input(component_id='selected_date', component_property='value')]
)
def update_graph(date_selected):
print(date_selected)
print(type(date_selected))
container = "The date chosen by user was: {}".format(date_selected)
dff = df.copy()
dff = dff[dff["date"] == date_selected]
# Plotly Express
fig = px.choropleth_mapbox(
data_frame = dff,
locations = 'state',
geojson = india_states,
range_color=(-1, 1),
color = 'vader_score',
mapbox_style = "carto-positron",
color_continuous_scale = px.colors.diverging.RdBu,
color_continuous_midpoint = 0,
center = {'lat': 24, 'lon': 78},
zoom = 2.85,
labels = {'vader_score': 'Sentiment Score'},
title = "Sentiment Map"
)
return container, fig
# --------------------------------
if __name__ == '__main__':
app.run_server(debug=True)
解决方案
数据源
- 使用公开可用的geojson几何
- 在仪表板应用程序中为日期生成情绪数据的数据框
- NB state列对应geojson中的ID
import requests
import pandas as pd
import numpy as np
import plotly.express as px
# fmt off
india_states = requests.get("https://raw.githubusercontent.com/Subhash9325/GeoJson-Data-of-Indian-States/master/Indian_States").json()
df = pd.DataFrame({"name":['Andaman and Nicobar', 'Andhra Pradesh', 'Arunachal Pradesh',
'Assam', 'Bihar', 'Chandigarh', 'Chhattisgarh',
'Dadra and Nagar Haveli', 'Daman and Diu', 'Delhi', 'Goa',
'Gujarat', 'Haryana', 'Himachal Pradesh', 'Jammu and Kashmir',
'Jharkhand', 'Karnataka', 'Kerala', 'Lakshadweep',
'Madhya Pradesh', 'Maharashtra', 'Manipur', 'Meghalaya', 'Mizoram',
'Nagaland', 'Orissa', 'Puducherry', 'Punjab', 'Rajasthan',
'Sikkim', 'Tamil Nadu', 'Tripura', 'Uttar Pradesh', 'Uttaranchal',
'West Bengal'],
"state":[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,
35]})
df = pd.concat([df.assign(date=d, vader_score=np.random.uniform(-1,1,len(df))) for d in [20200320, 20200325, 20200327, 20200330]])
# fmt on
破折号应用
- 这样的问题不在于破折号,而是创建Plotly Express 人物
- 数据框状态列需要链接到geonjson中的一个id
featureidkey="properties.ID_1"
https://plotly.com/python/mapbox-county-choropleth/#indexing-by-geojson-properties
# importing libraries
import dash
from dash import Dash, dcc, html, Input, Output
import plotly.express as px
import pandas as pd
from jupyter_dash import JupyterDash
# app = Dash(__name__)
app = JupyterDash(__name__)
# ------------------------------------------------------------------------------
# App layout
app.layout = html.Div(
[
html.H1(
"Sentiment Timeline for Covid-19 in India 2021-22",
style={"text-align": "center"},
),
dcc.Dropdown(
id="selected_date",
options=[
{"label": "March 20, 2020", "value": 20200320},
{"label": "March 25, 2020", "value": 20200325},
{"label": "March 27, 2020", "value": 20200327},
{"label": "March 30, 2020", "value": 20200330},
],
multi=False,
value=20200320,
style={"width": "40%"},
),
html.Div(id="output_container", children=[]),
html.Br(),
dcc.Graph(id="sentiment_map", figure={}),
]
)
# ------------------------------------------------------------------------------
# Connect the Plotly graphs with Dash Components
@app.callback(
[
Output(component_id="output_container", component_property="children"),
Output(component_id="sentiment_map", component_property="figure"),
],
[Input(component_id="selected_date", component_property="value")],
)
def update_graph(date_selected):
print(date_selected)
print(type(date_selected))
container = "The date chosen by user was: {}".format(date_selected)
dff = df.copy()
dff = dff[dff["date"] == date_selected]
# Plotly Express
fig = px.choropleth_mapbox(
data_frame=dff,
locations="state",
geojson=india_states,
featureidkey="properties.ID_1",
range_color=(-1, 1),
color="vader_score",
mapbox_style="carto-positron",
color_continuous_scale=px.colors.diverging.RdBu,
color_continuous_midpoint=0,
center={"lat": 24, "lon": 78},
zoom=2.85,
labels={"vader_score": "Sentiment Score"},
title="Sentiment Map",
)
return container, fig
# --------------------------------
if __name__ == "__main__":
# app.run_server(debug=True)
app.run_server(mode="inline")
推荐阅读
- eclipse - Eclipse中如何查看Java类的源代码而不用ctrl+click?
- ruby - 如何在 Ruby 中实现自定义变异方法?
- javascript - 如何根据 colspan 属性的值删除 HTML 表 td?
- symfony4 - 使用私有方法在 Symfony 中测试服务
- python - 在 NLTK Brown Corpus 上训练 Gensim word2vec 时遇到问题
- c++ - 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出?
- python - 如何配置 uWSGI 以便使用 pdb 进行调试(--honour-stdin 配置问题)
- rest - 我应该使用接受 http 标头还是更明确的 rest api 资源来定义客户端请求的数据格式?
- android - 可以在内部测试轨道上测试 Google Play 游戏服务吗?
- python - 使用 beautifulsoup 隐藏元素进行网页抓取