Plotly-dash graph not showing values - python

I am trying to create some chart using Dash for Python. I have some file with values that I want to read in, save the values in a list and use it to create the graph. My code:
app = dash.Dash()
app.layout = html.Div([
html.H1('Title'),
dcc.Dropdown(
id='my-dropdown',
options=[
{'label': 'Fruit', 'value': 'FRUIT'}
# {'label': 'Tesla', 'value': 'TSLA'},
# {'label': 'Apple', 'value': 'AAPL'}
],
value='TEMPERATUR'
),
dcc.Slider(
min=-5,
max=10,
step=0.5,
value=-3,
),
dcc.Graph(id='my-graph', animate=True),
])
path = "/../example.csv"
with open(path,"r") as file:
reader = csv.reader(file)
dataCopy=[]
for line in file:
dataCopy.append(line)
arrayValues = np.array(dataCopy)
#app.callback(Output('my-graph', 'figure'), [Input('my-dropdown', 'value')])
def update_graph(selected_dropdown_value):
return {
'data': arrayValues }
if __name__ == '__main__':
app.run_server(
)
When I print the arrayValues I get:
['28.687', '29.687', '24.687', '21.687', '25.687', '28.687']
But when I check my graph it has no values shown on it. Do you know what could my mistake be?
UPDATE: I tried with the line
arrayValues = list(map(float, arrayValues))
after getting it as a suggestion in the comments, but still no workable code.

You need to provide some additional information to the Graph data field,
If you want the arrayValues to be plotted in Y axis in a line graph the following code should work.
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
import plotly.graph_objs as go
#hardcoding arrayValues since csv is not provided
arrayValues = ['28.687', '29.687', '24.687', '21.687', '25.687', '28.687']
app = dash.Dash()
app.layout = html.Div([
html.H1('Title'),
dcc.Dropdown(
id='my-dropdown',
options=[
{'label': 'Fruit', 'value': 'FRUIT'}
# {'label': 'Tesla', 'value': 'TSLA'},
# {'label': 'Apple', 'value': 'AAPL'}
],
value='TEMPERATUR'
),
dcc.Slider(
min=-5,
max=10,
step=0.5,
value=-3,
),
dcc.Graph(id='my-graph', animate=True),
])
#path = "/../example.csv"
#with open(path,"r") as file:
# reader = csv.reader(file)
# dataCopy=[]
# for line in file:
# dataCopy.append(line)
# arrayValues = np.array(dataCopy)
#app.callback(Output('my-graph', 'figure'), [Input('my-dropdown', 'value')])
def update_graph(selected_dropdown_value):
return {
'data': [
{'y': arrayValues}
]
}
if __name__ == '__main__':
app.run_server(
)
As Dash uses plotly graph representation, you can refer to the official plotly docs to a variety of such Graphs.
Here is the documentation,
https://plot.ly/python/basic-charts/

Related

Dash python dynamic

I try to do a dashboard on python dash.
I succeeded the front-end. Indeed, I made appear a "year selector" but I do not understand how to change the graph depending on this year selector. Is anyone has idea or an explaination ? Thanks a lot.
#
# Imports
#
import plotly_express as px
import dash
import dash_core_components as dcc
import dash_html_components as html
#
# Data
if __name__ == '__main__':
app = dash.Dash(__name__) # (3)
fig = px.bar(df2, x="dpe", y="Percentage", color="signature") # (4)
app.layout = html.Div(children=[
html.H1(children=f'Répartition des Leads DEC',
style={'textAlign': 'center', 'color': '#7FDBFF'}), # (5)
html.Label('Year'),
dcc.Dropdown(
id="year-dropdown",
options=[
{'label': '2019', 'value': 2019},
{'label': '2020', 'value': 2020},
{'label': '2021', 'value': 2021},
{'label': '2022', 'value': 2022},
],
value=2022,
),
dcc.Graph(
id='graph1',
figure=fig
), # (6)
html.Div(children=f'''
This a graph which show the repartition of the DPE
'''), # (7)
]
)
#
# RUN APP
#
app.run_server(debug=False, port =4056) # (8)```
You need to use callbacks for the selection of dropdowns to appear. Check out the official documentation
You need to use callback to make you fig be interactive:
Change your dcc.Graph to: dcc.Graph(id='graph1',figure={})
Call back
#app.callback(Output('graph1', 'figure'),[Input('year-dropdown', 'value')]) def update_graph_1(year_dropdown): df2 = df2[(df2['Year'] == year_dropdown)] (# I dont see your dataframe so you will need to change this code) fig = px.bar(df2, x="dpe", y="Percentage", color="signature") return fig

Create dcc.Dropdown values Dynamically with Python Function

I am creating a search application with Dash by Plotly. I have a main search function for that creates a dataframe for the whole application that is defined as:
def search(term):
with index.searcher() as searcher:
parser = QueryParser("content", index.schema)
myquery = parser.parse(term)
results = searcher.search(myquery, limit=None)
print("Documents Containing ", term, ": ", len(results), "\n")
df = pd.DataFrame([i['date'], i['site'], i['system'], i['ticket'], i.score, i['level'], i['first'], i['last'], i['department'], \
i['detect'], i['code'],i['content'], i['description'], i['owner'], i['ownerGroup'], i['docId']] for i in results)
df.columns=['Reported Date', 'Site', 'System','Ticket ID', 'Score', 'Level', 'First', 'Last', 'Department', \
'Detection', 'Code', 'Content', 'Description', 'Owner', 'Owner Group', 'Document ID']
return df
I want users to be able to filter down search results with filters built into dcc.Dropdown. A couple of them can be hard-coded like so:
dcc.Dropdown(
id='siteFilter',
options=[
{'label': 'ABC', 'value': 'ABC'},
{'label': 'DEF', 'value': 'DEF'},
{'label': 'HIJ', 'value': 'HIJ'},
{'label': 'LMO', 'value': 'LMO'}
],
value=['ABC', 'DEF', 'HIJ', 'LMO'],
multi=True
However, some of the fields I want to filter on contain many options for a search and cannot be hard-coded. I can get the options to work. However, my application will not apply the filter changing when a user changes values. So, I have in my app.layout:
html.Div(dbc.Row([dbc.Col([
html.Label(["System Filter",
dcc.Dropdown(
id='systemFilter',
options='options',
value='All',
multi=True,
)
])
], width = 5)
]))
In my callback, I have tried several different options/combos of Outputs and States to achieve this with no luck. Callback:
#app.callback(
[Output(component_id='outTable', component_property='data'),
Output(component_id='outTable', component_property='columns'),
Output(component_id='commonWords', component_property='children'),
Output(component_id='systemFilter', component_property='options'),
#Output(component_id='systemFilter', component_property='value')
],
[Input(component_id='button', component_property='n_clicks')],
[State('searchId', 'value'),
State('siteFilter', 'value'),
State('detectFilter', 'value'),
State('levelFilter', 'value'),
State('codeFilter', 'value'),
#State(component_id='systemFilter', component_property='value')
])
def tableCreate(n_clicks, searchId, siteFilter, detectFilter, levelFilter, codeFilter):
if n_clicks > 0:
searchFrame = search(searchId)
###################### System Filter #######################################
#print('HERE DLKFSJSLDFKJSLDKJFJLKFDSJLDSKF')
#print(searchFrame['System'].unique())
#global optionsArray
optionsArray = searchFrame['System'].unique()
optionsArray = optionsArray.tolist()
print('Test')
print(optionsArray)
print('Test')
system_filter_options = [{'label': i, 'value': i} for i in optionsArray]
systemFilter = optionsArray
searchFrame = searchFrame[searchFrame['System'].isin(systemFilter)]
# Bunch of other code
searchFrame = searchFrame.drop(columns=['ContentNoStop'])
columns = [{'name': col, 'id': col} for col in searchFrame.columns]
data = searchFrame.to_dict(orient='records')
return data, columns, wordComponent, system_filter_options #, systemFilter
else:
return dash.no_update, dash.no_update, dash.no_update, dash.no_update
Essentially, one of 2 things happens. 1) The values return blank because they are not defined or 2) the options continually override the updated value parameter which I know is caused by the line systemFilter = optionsArray but I cannot seem to figure out a work around for this.
Here is an example image. I would like the results to populate all, but when a user filters by system and only selects a few, all my graphs and tables should update. But everytime, it does not seem to catch that. What am I missing here? How can the dcc.Dropdown selections be applied as a filter dynamically? I cannot and do not want to hard-code all the options
Easier reproduceable example:
I would like the dropdowns options to filter the table. If dog is selected, the table only shows dog.
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_table
import pandas as pd
from dash.dependencies import Input, Output, State
external_stylesheets = [dbc.themes.BOOTSTRAP]
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server
def createTable():
df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
'num_wings': [2, 0, 0, 0],
'system': ['falcon', 'dog', 'spider', 'fish']},
index=[1, 2, 3, 4])
return df
app.layout = html.Div([
html.Button('Submit and Refresh', id='button', n_clicks=0, className='btn btn-primary'),
dbc.Row([dbc.Col([
html.Label(["System Filter",
dcc.Dropdown(
id='systemFilter',
options='options',
value='All',
multi=True,
)
])
], width = 5)
]),
html.Div([dash_table.DataTable(style_cell={
'whiteSpace': 'normal',
'height': 'auto',
'textAlign': 'left'
},
fill_width=False,
id='outTable',
sort_action="native",
sort_mode="multi",
column_selectable="single",
row_deletable=True,
)
],
) ])
#app.callback(
[Output(component_id='outTable', component_property='data'),
Output(component_id='outTable', component_property='columns'),
Output(component_id='systemFilter', component_property='options'),
#Output(component_id='systemFilter', component_property='value')
],
[Input(component_id='button', component_property='n_clicks')],
[
State(component_id='systemFilter', component_property='value')
])
def tableCreate(n_clicks, systemFilter):
if n_clicks > 0:
searchFrame = createTable()
optionsArray = searchFrame['system'].unique()
optionsArray = optionsArray.tolist()
print('Test')
print(optionsArray)
print('Test')
system_filter_options = [{'label': i, 'value': i} for i in optionsArray]
systemFilter = optionsArray
searchFrame = searchFrame[searchFrame['system'].isin(systemFilter)]
columns = [{'name': col, 'id': col} for col in searchFrame.columns]
data = searchFrame.to_dict(orient='records')
return data, columns, system_filter_options#, systemFilter
if __name__ == '__main__':
app.run_server(debug=False)

Dynamically update the title in Dash Plotly

I have created this very simplified example in which I would like to dynamically update the title of a chart as a dropdown label changes.
Here's the code:
data = {'Stock': ['F', 'NFLX', 'AMZN'], 'Number': [10, 15, 7]}
df = pd.DataFrame(data, columns=['Stock', 'Number'])
stock_options = df['Stock']
app = dash.Dash(__name__)
app.layout = html.Div(children=[
html.H1(children='Example Bar Chart'),
html.Div([
dcc.Dropdown(
id='dropdown',
options=[{'label': i, 'value': i} for i in stock_options],
value='F',
),
html.Div(dcc.Graph(id='graph')),
]),
])
#app.callback(
Output(component_id='graph', component_property='figure'),
Input(component_id='dropdown', component_property='value')
)
def update_graph(stock):
msk = df.Stock.isin([stock])
figure = px.bar(df[msk], x='Stock', y='Number', title=f"{stock} open price")
return figure
if __name__ == '__main__':
app.run_server(debug=True)
So, while keeping the same label in dropdown instead of 'F open price' in the title I would like to get 'Facebook open price'... and so on.
I've tried to solve this with map but I couldn't get it working. Can someone point me in the direction on how to resolve this?
Thanks in advance.
As I wrote in my comment, not sure how you want to store the mapping between symbol name and the displayed title in the graph. Here is one solution that works using a dictionary stock_name_mapping that contains the symbols als keys and the displayed names as values:
import pandas as pd
import dash
from dash.dependencies import Input, Output
import dash_html_components as html
import dash_core_components as dcc
import plotly.express as px
data = {'Stock': ['F', 'NFLX', 'AMZN'], 'Number': [10, 15, 7]}
df = pd.DataFrame(data, columns=['Stock', 'Number'])
stock_options = df['Stock']
stock_name_mapping = {'F': 'Facebook',
'NFLX': 'Netflix',
'AMZN': 'Amazon'}
app = dash.Dash(__name__)
app.layout = html.Div(children=[
html.H1(children='Example Bar Chart'),
html.Div([
dcc.Dropdown(
id='dropdown',
options=[{'label': i, 'value': i} for i in stock_options],
value='F',
),
html.Div(dcc.Graph(id='graph')),
]),
])
#app.callback(
Output(component_id='graph', component_property='figure'),
Input(component_id='dropdown', component_property='value')
)
def update_graph(stock):
msk = df.Stock.isin([stock])
stock_name = stock_name_mapping[stock]
figure = px.bar(df[msk], x='Stock', y='Number', title=f"{stock_name} open price")
return figure
if __name__ == '__main__':
app.run_server(debug=True)

Create Dropdown with label and values using panda library and Dash Plotly in python

I am using panda library in Python to read from a csv file and fill a Dropdown. My application uses Dash Plotly to create a HTML web interface. I am filling with only the values of the Dropdown, the labels of the Dropdown are the same of the values. How do I change the labels to be the text from the csv file?
available_rpi.csv
ip,name
192.168.1.6,"Virtual I²C (192.168.1.6)"
192.168.1.102,"GPS UART (192.168.1.102)"
192.168.1.106,"Ultrasonic I²C (192.168.1.103)"
python script:
import dash,requests,pandas as pd
df = pd.read_csv('available_rpi.csv', usecols = ['ip','name'])
available_rpi = df['ip'].unique()
app.layout = html.Div( [
html.H1(children='RESENSE'),
html.Div(children='''RESENSE: Transparent Record and Replay in the Internet of Things (IoT).'''),
# html.Div(['Name : ', dcc.Input(id='input',value='ACC',type='text') ]),
# dcc.Markdown(''' '''),
html.Label('Raspberry Pi'),
dcc.Dropdown(
id = "input",
options=[{'label': i, 'value': i} for i in available_rpi],
value=''
),
html.Div(id='output'),
# Graph for arriving data (static)
dcc.Graph(id='data', animate=True),
dcc.Interval(id='graph-update',interval=2*1000)
])
How about reading the CSV data in a bit different way with pandas and storing it in a dictionary?
import dash
import pandas as pd
import dash_core_components as dcc
import dash_html_components as html
df = pd.read_csv('available_rpi.csv', usecols = ['ip','name'])
available_rpi = df.to_dict('records')
app = dash.Dash(__name__)
app.layout = html.Div( [
html.H1(children='RESENSE'),
html.Div(children='''RESENSE: Transparent Record and Replay in the Internet of Things (IoT).'''),
# html.Div(['Name : ', dcc.Input(id='input',value='ACC',type='text') ]),
# dcc.Markdown(''' '''),
html.Label('Raspberry Pi'),
dcc.Dropdown(
id = "input",
options=[{'label': i['name'], 'value': i['ip']} for i in available_rpi],
value=''
),
html.Div(id='output'),
# Graph for arriving data (static)
dcc.Graph(id='data', animate=True),
dcc.Interval(id='graph-update',interval=2*1000)
])
if __name__ == '__main__':
app.run_server()
You should store your .csv file as a list of dictionaries using orient='records' and then use a list comprehension to set your options for your Dropdown component:
import dash
import pandas as pd
import dash_core_components as dcc
import dash_html_components as html
available_rpi = pd.read_csv('available_rpi.csv').to_dict(orient='records')
app = dash.Dash(__name__)
app.layout = html.Div([
html.H1(children='RESENSE'),
html.Div(children='''RESENSE: Transparent Record and Replay in the Internet of Things (IoT).'''),
html.Label('Raspberry Pi'),
dcc.Dropdown(
id = "input",
options=[{'label': i['name'], 'value': i['ip']} for i in available_rpi],
value=''
),
html.Div(id='output'),
#Graph for arriving data (static)
dcc.Graph(id='data', animate=True),
dcc.Interval(id='graph-update',interval=2*1000)
])
if __name__ == '__main__':
app.run_server()
I have to use a dictionary....
available_rpi = pd.read_csv('available_rpi.csv', header=None, dtype={0: str}).set_index(0).squeeze().to_dict()
#print("Raspberry Pi's available:")
#for key, car in available_rpi.items():
# print('{} : {}'.format(key, car))
app.layout = html.Div( [
html.H1(children='RESENSE'),
html.Div(children='''RESENSE: Transparent Record and Replay in the Internet of Things (IoT).'''),
# html.Div(['Name : ', dcc.Input(id='input',value='ACC',type='text') ]),
# dcc.Markdown(''' '''),
html.Label('Raspberry Pi'),
dcc.Dropdown(
id = "input",
options=[{'label': v, 'value': k} for k, v in available_rpi.items()],
value=''
),
html.Div(id='output'),
# Graph for arriving data (static)
dcc.Graph(id='data', animate=True),
dcc.Interval(id='graph-update',interval=2*1000)
])

API defined dataframe (dynamically generated) into Table (Dash_Table_Experiments)

Does anyone know how to dynamically generate a TABLE of data based on the user input using Dash_Table_Experiments (Python code)?
This code is static, however, I would like to find a way to make it dynamic. Thus, when a user enters a ticker symbol the TABLE will automatically update with the pertinent data below the chart.
The dataframe will change because it is generated from an api (i.e. Alpha Vantage), thus it cannot be defined as a static table. See code below.
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table_experiments as dt
import json
import pandas as pd
from alpha_vantage.timeseries import TimeSeries
print(dcc.__version__) # 0.6.0 or above is required
app = dash.Dash()
ts = TimeSeries(key='', output_format='pandas')
data1, meta_data = ts.get_daily(symbol=inputsymbol, outputsize='full')
date=data1.reset_index(level=['date'])
df=(date.tail(10))
DF_SIMPLE = df
app.config.supress_callback_exceptions = True
app.scripts.config.serve_locally = True
app.layout = html.Div([
dcc.Location(id='url', refresh=False),
html.Div(id='page-content'),
html.Div(dt.DataTable(rows=[{}]), style={'display': 'none'})
])
index_page = html.Div([
html.H1('Page Home'),
html.Br(),
dcc.Link('Go to Home', href='/'),
html.Br(),
dcc.Link('Go to Page 1', href='/page-1'),
])
page_1_layout = html.Div([
html.H1('Page 1'),
html.Br(),
dcc.Link('Go back to home', href='/'),
html.H4('DataTable'),
dt.DataTable(
rows=DF_SIMPLE.to_dict('records'),
# optional - sets the order of columns
#columns=sorted(DF_SIMPLE.columns),
editable=False,
id='editable-table'
),
html.Div([
html.Pre(id='output', className="two columns"),
html.Div(
dcc.Graph(
id='graph',
style={
'overflow-x': 'wordwrap'
}
),
className="ten columns"
)
], className="row"),
])
#app.callback(
dash.dependencies.Output('output', 'children'),
[dash.dependencies.Input('editable-table', 'rows')])
def update_selected_row_indices(rows):
return json.dumps(rows, indent=2)
#app.callback(
dash.dependencies.Output('graph', 'figure'),
[dash.dependencies.Input('editable-table', 'rows')])
def update_figure(rows):
dff = pd.DataFrame(rows)
return {
'data': [{
'x': dff['x'],
'y': dff['y'],
}],
'layout': {
'margin': {'l': 10, 'r': 0, 't': 10, 'b': 20}
}
}
# Update the index
#app.callback(dash.dependencies.Output('page-content', 'children'),
[dash.dependencies.Input('url', 'pathname')])
def display_page(pathname):
if pathname == '/page-1':
return page_1_layout
else:
return index_page
app.css.append_css({
'external_url': 'https://codepen.io/chriddyp/pen/bWLwgP.css'
})
if __name__ == '__main__':
app.run_server(debug=True)

Categories

Resources