#python #plotly-dash
Вопрос:
Я пытаюсь создать диаграмму сосулек, которая отображается в приложении Dash. Мои исходные данные считываются во фреймы данных из файла excel. При запуске кода в скрипте с использованием определенного фрейма данных диаграмма сосульки отображается правильно, но при попытке интегрировать ее в интерактивное приложение Dash график вообще не отображается. Мой код выглядит следующим образом, проблема находится на 2-м рисунке (рис. 2):
##Create a reactive dashboard with drop down menus in Dash
#Import all the necessary modules
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
from jupyter_dash import JupyterDash
import plotly.graph_objects as go
import pandas as pd
from dash.dependencies import Input, Output
#Create a dictionary containing the data frames per year
Dict_dfs = {2015: df_n_2015,
2016: df_n_2016,
2017: df_n_2017,
2018: df_n_2018,
2019: df_n_2019,
2020: df_n_2020}
Dict_dfs_hr = {2015: df_2015_hr,
2016: df_2016_hr,
2017: df_2017_hr,
2018: df_2018_hr,
2019: df_2019_hr,
2020: df_2020_hr}
#Load an external stylesheet
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
#Initiate the Dash app in the jupyter environment
app = JupyterDash(__name__, external_stylesheets=external_stylesheets)
#Create the app layout
app.layout = html.Div(children=[
# All elements from the top of the page
html.Div([
#Header
html.H1(children='EYDAP consumption analytics'),
#Create the subheading
html.Div(children='''
An interactive graph visualising the IWA consumption components per year.
Select a year of interest:
'''),
#Create the dropdown menu
dcc.Dropdown(
id='demo-dropdown',
options=[
#create the dropdown labels (water balance year of reference)
{'label': k, 'value': k} for k in range(2015,2021)
],
value = 2015
)
]),
#Place the graphs
html.Div([
dcc.Graph(
id='graphIWA_bar'
),
]),
html.Div([
dcc.Graph(
id='graphIWA_icicle'
),
]),
html.Div([
dcc.Graph(
id='graphIWA_sankey'
),
]),
])
#Create the Dash calbback, make the app reactive
@app.callback(
Output('graphIWA_bar', 'figure'),
Output('graphIWA_icicle', 'figure'),
Output('graphIWA_sankey', 'figure'),
[Input('demo-dropdown', 'value')])
#Define the function that updates the graph
def update_figure(year):
#Return the data frame for the year of reference
df = Dict_dfs[year]
df_hr = Dict_dfs_hr[year]
#Initiate the figure object
fig1 = go.Figure()
#Loop to add a bar for every IWA component (e.g., SIV, BC, etc.)
for k in ['SIV', 'BC', 'NRW', 'WL','UAC']:
fig1.add_bar(
x=df['Month'],
y=df[k],
name=k
)
#Update the figure layout in order to add the title , the axes titles, a button list that enables
#a component selection, etc.
fig1.update_layout(
title = 'IWA Breakdown: Bar Chart',
barmode='group',
yaxis_title='Volume of Water in mu00b3',
legend_title='Legend',
updatemenus=[go.layout.Updatemenu(
active=0,
buttons=list(
[dict(label = 'All',
method = 'update',
args = [{'visible': [True, True, True, True, True]},
{'title': 'All',
'showlegend':True}]),
dict(label = 'SIV',
method = 'update',
args = [{'visible': [True, False, False, False, False]},
{'title': 'SIV',
'showlegend':True}]),
dict(label = 'BC',
method = 'update',
args = [{'visible': [False, True, False, False, False]},
{'title': 'BC',
'showlegend':True}]),
dict(label = 'NRW',
method = 'update',
args = [{'visible': [False, False, True, False, False]},
{'title': 'NRW',
'showlegend':True}]),
dict(label = 'WL',
method = 'update',
args = [{'visible': [False, False, False, True, False]},
{'title': 'WL',
'showlegend':True}]),
dict(label = 'UAC',
method = 'update',
args = [{'visible': [False, False, False, False, True]},
{'title': 'UAC',
'showlegend':True}]),
])
)
])
data_fr_dict = dict(
ids=df_hr['Item and Group'],
parents=df_hr['Parent'],
values=df_hr['Value'],
labels=df_hr['Label'],
branchvalues='total',
root_color='lightgrey'
)
fig2 = go.Figure(go.Icicle(
data_fr_dict
))
fig2.update_layout(title = 'IWA Breakdown: Icicle Chart',
margin = dict(t=50, l=25, r=25, b=25))
#Sankey figure
# Get the data in the format Plotly wants
label_dict = { df_hr["Item and Group"][i] : i for i in range(0, len(df_hr) ) }
# Initialize empty arrays
source = []
target = []
value = []
for i, row in df_hr.iterrows():
# Skip the root level
if row["Item and Group"] != 'SIV':
source.append(label_dict[row['Parent']])
target.append(label_dict[row["Item and Group"]])
value.append(row["Value"])
# Plot the figure
fig3 = go.Figure(data=[go.Sankey(
valueformat = ".2f",
node = dict(
pad = 50,
thickness = 20,
line = dict(color = "black", width = 0.5),
label = df_hr["Item and Group"].to_list(),
color = "blue",
hovertemplate='%{label} is %{value} Million mu00b3',
),
link = dict(
source = source,
target = target,
value = value
))])
fig3.update_layout(title='IWA Breakdown: Sankey Chart')
return fig1, fig2, fig3
#Run the app server
if __name__ == '__main__':
app.run_server(debug=True)
Желаемый результат выглядит следующим образом:
Результат, полученный моим кодом, выглядит следующим образом:
Комментарии:
1. Какая версия dash? Попробуйте обновить. Это сработало для меня после обновления.