Plotly dash table add rows and update input data - python

I'm trying to make a dash table based on input data but I'm stucking in add more rows to add new inputs. Actually I read this docs and I know that I can directly input in dash table but I want to update dash table from input.
Below is my code:
import pandas as pd
import numpy as np
from datetime import datetime as dt
import plotly.express as px
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output, State
import dash_table
import dash_bootstrap_components as dbc
from dash_extensions import Download
from dash_extensions.snippets import send_data_frame
import glob
import os
from pandas.tseries.offsets import BDay
import plotly.graph_objects as go
app = dash.Dash(__name__)
MD23 = pd.DataFrame({'Number':[],
'PW':[],
'Name 1':[],
'Name 2':[],
'Email':[],
'Web':[],
'Abc':[]})
# ------------------------------------------------------------------------
input_types = ['number', 'password', 'text', 'tel', 'email', 'url', 'search']
app.layout = html.Div([
html.Div([
dcc.Input(
id='my_{}'.format(x),
type=x,
placeholder="insert {}".format(x), # A hint to the user of what can be entered in the control
minLength=0, maxLength=50, # Ranges for character length inside input box
autoComplete='on',
disabled=False, # Disable input box
readOnly=False, # Make input box read only
required=False, # Require user to insert something into input box
size="20", # Number of characters that will be visible inside box
) for x in input_types
]),
html.Br(),
html.Button('Add Row',id='add_row',n_clicks=0),
dbc.Row([
dbc.Col([html.H5('List',className='text-center'),
dash_table.DataTable(
id='table-container_3',
data=[],
columns=[{"name":i_3,"id":i_3,'type':'numeric'} for i_3 in MD23.columns],
style_table={'overflow':'scroll','height':600},
style_cell={'textAlign':'center'},
row_deletable=True,
editable=True)
],width={'size':12,"offset":0,'order':1})
]),
])
#app.callback(Output('table-container_3', 'data'),
[Input('my_{}'.format(x),'value')for x in input_types])
def update_data(selected_number, selected_pw,
selected_text, selected_tel,
selected_email,selected_url,
selected_search):
data = pd.DataFrame({'Number':[selected_number],
'PW':[selected_pw],
'Name 1':[selected_text],
'Name 2':[selected_tel],
'Email':[selected_email],
'Web':[selected_url],
'Abc':[selected_search]})
return data.to_dict(orient='records')
# ------------------------------------------------------------------------
if __name__ == '__main__':
app.run_server(debug=False)
I tried to add rows as below but it's not worked:
#app.callback(
Output('table-container_3', 'data'),
Input('add_row', 'n_clicks'),
State('table-container_3', 'data'),
State('table-container_3', 'columns'))
def add_row(n_clicks, rows, columns):
if n_clicks > 0:
rows.append()
return rows
I really need suggestions to solve this problem. Thank you so much.

tran
Try to replace your callback with this callback:
#app.callback(
Output('table-container_3', 'data'),
Input('add_row', 'n_clicks'),
[State('table-container_3', 'data'),
State('table-container_3', 'columns')]+
[State('my_{}'.format(x), 'value') for x in input_types])
def add_row(n_clicks, rows, columns, selected_number, selected_pw,
selected_text, selected_tel,
selected_email, selected_url,
selected_search):
if n_clicks > 0:
rows.append({c['id']: r for c,r in zip(columns, [selected_number, selected_pw, selected_text, selected_tel, selected_email, selected_url, selected_search])})
return rows

Related

update DataFrame in Dash after text input

I want to update my DataFrame that feeds my graphs in realtime. In all the tutorials I have found, the DataFrame is created before creating the app layout. I want to take the input from the input component with the username_input ID and use that in the get_dataFrame function to create my initial DataFrame which will create the figure which will be used in the graph component.
app = Dash(__name__)
df = get_dataFrame(username_input)
fig = px.line(df, x='end', y="user",color="class")
app.layout = html.Div(children=[
dcc.Input(
id="username_input",
placeholder="username",
type='text'
),
dcc.Graph(
id='example-graph',
figure=fig
),
])
I don't fully understand how to structure the code so that this is possible. In essence I want a user input first and then after the user input all the dash data updates to reflect the new input. Any ideas?
Move your dataframe and figure creation into your callback, then return a new figure after the user's input comes in. Working example:
from dash import Dash, dcc, html, Input, Output, no_update
import pandas as pd
import plotly.express as px
import numpy as np
app = Dash(__name__)
def get_dataFrame(username_input):
data = np.random.rand(10) * len(username_input)
return pd.DataFrame({"end": [*range(10)], "user": data, "class": ["red"] * 10})
fig = px.line()
app.layout = html.Div(
children=[
dcc.Input(id="username_input", placeholder="username", type="text"),
dcc.Graph(id="example-graph", figure=fig),
]
)
#app.callback(
Output("example-graph", "figure"), Input("username_input", "value"),
)
def func(username_input: str):
if username_input:
df = get_dataFrame(username_input)
fig = px.line(df, x="end", y="user", color="class")
return fig
return no_update
if __name__ == "__main__":
app.run(debug=True)

Plotly Dash dcc.Interval fails after a while: Callback error updating graph.figure

I'm trying to set my Dash app to automatically pull the latest data from a .csv file used in the data frame with dcc.Interval. The error code isn't providing a detailed explanation and also doesn't always appear. I've tried this with both a button and a set 6 sec interval, but the result seems to be the same. The Dash app runs fine at first and refreshes fine a few times, then error starts occurring:
Callback error updating graph.figure
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
app = dash.Dash(__name__)
server = app.server
df = pd.read_csv('example.csv', encoding="WINDOWS-1252")
app.layout = html.Div([
dcc.Graph(id='graph'),
dcc.Interval(
id='interval-component',
interval=1*6000,
n_intervals=0
)
])
#app.callback(
Output('graph','figure'),
[Input('interval-component', 'n_intervals')]
)
def update_df(n):
updated_df = pd.read_csv('example.csv', encoding="WINDOWS-1252")
fig = px.scatter(updated_df, x='Date', y='Deviation', height=800)
fig.update_layout(
yaxis_tickformat = '.0%',
)
fig.update_xaxes(
rangeslider_visible=True,
rangeselector=dict(
)
)
return fig
if __name__ == '__main__':
app.run_server(debug=True)
I think your issue must have something to do with your file specifically, because the following code based exactly off as you provide (with the exception of generation of random matching-df timeseries data), works perfectly updating with an interval of every 6 seconds:
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
np.random.seed(2019)
def get_random_deviation_ts_df(N=100):
rng = pd.date_range("2019-01-01", freq="D", periods=N)
df = pd.DataFrame(np.random.rand(N, 1), columns=["Deviation"], index=rng)
df["Date"] = df.index
return df
app = dash.Dash(__name__)
server = app.server
# df = pd.read_csv('example.csv', encoding="WINDOWS-1252")
app.layout = html.Div(
[
dcc.Graph(id="graph"),
dcc.Interval(
id="interval-component", interval=1 * 6000, n_intervals=0
),
]
)
#app.callback(
Output("graph", "figure"), [Input("interval-component", "n_intervals")]
)
def update_df(n):
updated_df = (
get_random_deviation_ts_df()
) # pd.read_csv('example.csv', encoding="WINDOWS-1252")
fig = px.scatter(updated_df, x="Date", y="Deviation", height=800)
fig.update_layout(yaxis_tickformat=".0%",)
fig.update_xaxes(rangeslider_visible=True, rangeselector=dict())
return fig
if __name__ == "__main__":
app.run_server(debug=True)

How to use a boolean switch to update a graph in Dash?

I'm new in Dash. I'm trying to use a daq.BooleanSwitch() like an input to callback a graph. I can display a message but I have troubles with the graph.
Does anyone have any advice that can help me?
import dash
from dash.dependencies import Input, Output
import dash_daq as daq
import dash_html_components as html
app = dash.Dash(__name__)
app.layout = html.Div([
html.H1("Here we go"),
daq.BooleanSwitch(id='my_pb', on=False,color="red"),
html.Div(id='power-button-result-1'),
dcc.Graph(id="plot")
])
#app.callback(
Output('power-button-result-1', 'children'),
Input('my_pb', 'on')
)
def update_output(on):
x = '{}'.format(on)
if x == "True":
return "Hi Iḿ using DASH"
#app.callback(
Output('plot', 'figure'),
Input('my_pb', 'on')
)
def figura(on):
x = '{}'.format(on)
if x == "True":
# fig1 = Code to do a nice plot
return fig1
if __name__ == "__main__":
app.run_server(port = 1895)
My DASH output look like this:
I took a look at your code, and a couple changes were necessary:
import dash
import dash_daq as daq
from dash import dcc
from dash import html
from dash.dependencies import Input
from dash.dependencies import Output
app = dash.Dash(__name__)
app.layout = html.Div(
[
html.H1("Here we go"),
daq.BooleanSwitch(id="my_pb", on=False, color="red"),
html.Div(id="power-button-result-1"),
]
)
#app.callback(
Output("power-button-result-1", "children"),
Input("my_pb", "on"),
)
def update_output(on):
x = "{}".format(on)
if x == "True":
return [dcc.Graph(id="plot")]
if __name__ == "__main__":
app.run_server(debug=True)
You were super close - I think you only need one callback. Here, you can see the boolean switch now toggles the display (or not) of the dcc.Graph object. Is this what you were looking for?
↓ (toggle the switch)
If you want the graph to already be displayed, and then updated upon toggling, here's a slightly modified expanded version of same code above to do that:
import dash
import dash_daq as daq
from dash import dcc
from dash import html
from dash import no_update
from dash.dependencies import Input
from dash.dependencies import Output
import plotly.express as px
import pandas as pd
app = dash.Dash(__name__)
app.layout = html.Div(
[
html.H1("Here we go"),
daq.BooleanSwitch(id="my_pb", on=False, color="red"),
html.Div(
[dcc.Graph(id="plot")], id="power-button-result-1"
),
]
)
#app.callback(
Output("power-button-result-1", "children"),
Input("my_pb", "on"),
)
def update_output(on):
df = px.data.iris()
if on:
fig = px.scatter(df, x="sepal_width", y="sepal_length")
dcc.Graph(figure=fig)
return [dcc.Graph(figure=fig)]
else:
fig = px.scatter()
return [dcc.Graph(figure=fig)]
if __name__ == "__main__":
app.run_server(debug=True)
There - that's much better, hopefully helpful?

Plotly in Dash Python is not getting updated

When I run the code i get the graph but the graph is not getting updated i am calling the data from my sql laptop sql management studio.
Kindly let me know what needs to be done the X axis contains date and time and Y axis contains data in numeric form which is getting updated automatically
Code:
import pandas as pd
import pyodbc
import numpy as np
server ='LAPTOP-OO3V36UA\SQLEXPRESS'
db='addy'
conn=pyodbc.connect('DRIVER={SQL Server}; SERVER=' +server + ';DATABASE=' + db +
';Trusted_connection=yes')
sql="""
SELECT * FROM Summry
"""
df=pd.read_sql(sql ,conn)
import dash
from dash.dependencies import Output, Input
import dash_core_components as dcc
import dash_html_components as html
from random import random
import plotly
app = dash.Dash(__name__)
app.layout = html.Div([
dcc.Graph(id='live-update-graph-scatter', animate=True),
dcc.Interval(
id='interval-component',
interval=1*1000
)
])
#app.callback(Output('live-update-graph-scatter', 'figure'),
[Input('interval-component', 'interval')])
def update_graph_scatter():
df=pd.read_sql(sql ,conn)
trace1=go.Scatter(
y=df['ACL'],
x = df['DateandnTime'],
mode='lines',
name='ACL'
)
layout = go.Layout(
title='Daily Monitoring'
)
return {'data': trace1, 'layout': layout}
if __name__ == '__main__':
app.run_server()
You've set your callback's input to
Input('interval-component', 'interval')
But you want
Input('interval-component', 'n_intervals')
The interval property sets how frequently n_intervals gets updated. The change in n_intervals is what can be used to trigger the callback.
Here's the documentation: https://dash.plotly.com/dash-core-components/interval

How to subset and generate a large data frame with Python Dash?

I'm trying to create a Dash app that must:
Read a csv file and convert it to a dataframe
Subset this dataframe according to the user's choices (radio buttons,...)
Generate the subseted dataframe in a csv file
The issue is I can't subset the dataframe as I would like.
Let's imagine I got a data frame gas3 with a variable Flag. Here is a part of my code:
import dash
import dash_core_components as dcc # Graphs
import dash_html_components as html # Tags
from dash.dependencies import Input, Output, Event, State
from pandas_datareader import DataReader
import time
import pandas as pd
import plotly
import plotly.graph_objs as go
from collections import deque
import random
import os
import pandas as pd
import glob
import numpy as np
import statistics
from datetime import *
from pytz import *
import dash_table_experiments as dte
import io
from flask import send_file
import flask
import urllib.parse
# Import df
gas3 = pd.read_csv("D:/Path/gas3.csv", sep=';')
gas3['Date_Local_Time'] = pd.to_datetime(gas3['Date_Local_Time'], format='%Y/%m/%d %H:%M') # Conversion de la variable en type "date heure"
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets) # Starting application
app.layout = html.Div(children=[
# Radio buttons
html.Div([
html.Label("Sélectionnez la valeur du Flag que vous souhaitez :",
htmlFor='radioflag',
),
html.Br(),
html.Br(),
dcc.RadioItems(
id='radioflag',
options=[
{'label': 'Flag 0', 'value': 'Flag0'},
{'label': 'Flag 1', 'value': 'Flag1'},
{'label': 'Flag 3', 'value': 'Flag3'},
{'label': 'Chambre à flux', 'value': 'CAF'}
]
),
html.Br(),
]),
# Download button
html.Div(id='table'),
html.A(
'Download Data',
id='download-link',
download="rawdata.csv",
href="",
target="_blank"
)
])
### Subset function
def filter_data(flag):
gas_genere = gas3.copy()
if flag == 'Flag0':
gas_genere = gas_genere[gas_genere['Flag']==0]
return gas_genere
else:
return gas_genere[0:4]
# Callback
#app.callback(
Output('download-link', 'href'),
[Input('radioflag', 'value')])
def update_download_link(flag):
gas_genere = filter_data(flag)
csv_string = gas_genere.to_csv(index=False, encoding='utf-8', sep=';')
csv_string = "data:text/csv;charset=utf-8,%EF%BB%BF" + urllib.parse.quote(csv_string)
return csv_string
if __name__ == '__main__':
app.run_server(debug=True)
I found out the issue but I don't know how to fix it. If I change my filter_data function to (I just added [0:2] to the first return gas_genere) :
def filter_data(flag):
gas_genere = gas3.copy()
if flag == 'Flag0':
gas_genere = gas_genere[gas_genere['Flag']==0]
return gas_genere[0:2]
else:
return gas_genere[0:4]
The app works well! If I check "Flag 0", gas_genere[0:2] will be generated. Else, gas_genere[0:4] will be generated.
But if I keep it like in my original code, I can check "Flag 1", "Flag 3", "Chambre à flux" or don't check any button, it would work and generate gas_genere[0:4]. But if I check "Flag 0", instead of returning gas_genere, I would not get a csv file, but would get an error: "téléchargement Echec - Erreur réseau." which in English should be "Download Failed - Network Error".
I tryed to generate my dataframe gas_genere = gas3[gas3['Flag']==0] in Python and it got 14299 rows and 43 columns.
Is my dataframe too large? If so, what should I do?
Thank you!

Categories

Resources