'Waterfall chart is breaking when I use inputs from a data table in Dash App
I seem to be having a problem with my code where the visualization breaks after adding in certain numbers to the data table as an input. Can anyone help with where I am going wrong?
In particular, the callback works fine at first until you enter certain combinations of numbers. For me, if I enter these numbers into the 'value' column, it breaks the visual and flips the axis somehow.
This causes it to break: 1000 100 50 -400 -50 0
Here is the code:
'''
import dash
import pandas as pd
from dash import dash_table as dt
from dash import dcc
from dash import html
from dash.dependencies import Input
from dash.dependencies import Output
import plotly.express as px
import plotly.graph_objects as go
df_main = pd.DataFrame({'measure' : ["relative", "relative", "relative", "relative", "relative", "total"],
'title' : ["Sales", "Consulting", "Net revenue", "Purchases", "Other expenses", "Profit before tax"],
'label' : ["+60", "+150", "Sub Total", "-40", "-20", "Total"],
'value' : [60, 150, 50, -40, -20, 0]})
app = dash.Dash(__name__)
app.layout = html.Div(
children=[
dt.DataTable(
id="table-container",
columns=[{'name': 'measure', 'id': 'measure'},
{'name': 'title', 'id': 'title'},
{'name': 'label', 'id': 'label'},
{'name': 'value', 'id': 'value'}],
data=df_main.to_dict("records"),
editable=True
),
dcc.Graph(id='visual')
]
)
@app.callback(Output('visual', 'figure'),
Input("table-container", "data"),
Input("table-container", "columns"))
def display_graph(rows, columns):
df = pd.DataFrame(rows, columns=[c['name'] for c in columns])
fig = go.Figure(go.Waterfall(
base = 0,
orientation = "v",
measure = df['measure'],
x = df['title'],
textposition = "outside",
text = df['label'],
y = df['value'],
decreasing = {"marker":{"color":"#ef553b", }},
increasing = {"marker":{"color":"#00cc96"}},
totals = {"marker":{"color":"#636efa"}},
connector = {"line":{"color":"rgb(63, 63, 63)"}},
))
fig.update_layout(
title = "Profit and loss statement 2018",
showlegend = False
)
return fig
if __name__ == '__main__':
app.run_server(debug=True, use_reloader=False)
'''
Solution 1:[1]
I actually found a solution after messing around for quite some time. Dash tables must have some kind of data type change as a user inputs values. Adding a line of code to convert the value field into numeric did the trick...
df['value'] = pd.to_numeric(df['value'])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anthony Fleri |
