✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🧬 Learn how to build RNA-Seq data apps with Python & Dash. Register for the May 20 Webinar!

Callback pandas csv

Hello,

I have multiple graphs and pie charts that use data from pandas pd.read_csv.
I also have a dropdown menu at the top of the web page (which updates variable chosenmonth)

I have two csv files:
sales-jan.csv
sales-feb.csv

I would like the user on the website to be able to choose which CSV data they see by using a dropdown menu.
How can I do this?

Kindest Regards,
Joseph

The online documentation has plenty of examples on how to add/populate a dropdown so i won’t duplicate here. You can also use dcc.Store component(s) to hold the data from the 2 csv files. Then, within a callback that would create your graphs, you can pass the data via the state feature ( State('<your dcc.State component id>', 'data'). The callback could be triggered by the selection of the callback, and you can determine which selection was made by looking at the value property of the callback.

Depending on how you implement your solution, you can possibly benefit from dash.callback_context - It can be invoked at the start of a callback and provides a weath of info about the parameters of your callback.

If you have sample code that is not working, you can paste (using Markdown) and the forum is pretty good about providing feedback .

Hello flyingcujo,

Thanks for the response!

I’ve made a change so I now have a dcc.dropdown, and I have a callback which takes the dcc.dropdown in addition to a slider to change the figure of a pie chart. It works!

The only issue I have now is, I would like to do the same and update all my graphs depending on this input (the pie chart takes the slider input, but the other graphs do not).

Here’s what I have so far:

import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import pandas as pd
import plotly.graph_objs as go
from dash.dependencies import Input, Output

external_stylesheets = [‘https://codepen.io/chriddyp/pen/bWLwgP.css’]

app = dash.Dash(name, external_stylesheets=external_stylesheets)

df = pd.read_csv(‘pcl-sales-jan.csv’)
df2 = pd.read_csv(‘pcl-sales-feb.csv’)

app.layout = html.Div([
# Div1 - Heading
html.Div([
html.H1(‘PCL Performance Dashboard’),
dcc.Dropdown(
id=‘month-selector’,
placeholder=‘Select a month to view’,
options=[
{‘label’: ‘Jan’, ‘value’: ‘Jan’},
{‘label’: ‘Feb’, ‘value’: ‘Feb’},
{‘label’: ‘March’, ‘value’: ‘March’},
])]),

# Div2 - Output Display from Month Selector
html.Div(id='output-selection'),

# Div3 - Table
html.Div([
    html.P([html.Br()]),
    dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict('records'))
], className="row"),

# Div4 - Pie chart and slider
html.Div([
dcc.Graph(id='pcl-sales-pie',
          style={'width': '120%'}),
dcc.Slider(
id='date-slider',
min=df['Date'].min(),
max=df['Date'].max(),
value=df['Date'].min(),
marks={str(Date): str(Date) for Date in df['Date']},
step=None
)
], className= "five columns"),

# Div5 - History Graph
html.Div([
dcc.Graph(
    id='history-graph',
    figure={
        'data': [
            {'x': df['Date'], 'y': df['Orders Raised'], 'type': 'scatter', 'name': 'Orders Raised'},
            {'x': df['Date'], 'y': df['Orders Shipped'], 'type': 'scatter', 'name': 'Orders Shipped'},
        ],
        'layout': {
            'title': 'Sales History for Selected Month'
        }
    }),
], className="six columns"),

# Div6 - Forward Order/Back Order
html.Div([
dcc.Graph(
    id='forward-back-orders',
    figure={
        'data': [
            {'x': df['Date'], 'y': df['Forward Sheets'], 'type': 'scatter', 'name': 'Forward Orders'},
            {'x': df['Date'], 'y': df['Back Sheets'], 'type': 'scatter', 'name': 'Back Orders'},
        ],
        'layout': {
            'title': 'Sheets from Forward Orders vs Back Orders'
        }
    }),
], className="eleven columns"),
])

def find_date(dayofmonth):
for index, item in enumerate(df[‘Date’]):
if item == dayofmonth:
return index
return 0

@app.callback(
Output(‘pcl-sales-pie’, ‘figure’),
[Input(‘date-slider’, ‘value’),
Input(‘month-selector’, ‘value’)])

def update_figure(date_slider_value, month_selector_value):
ndx = find_date(date_slider_value)

# if None is selected
if month_selector_value == 'None':
    df = pd.read_csv('pcl-sales-jan.csv')

# if Jan is selected
if month_selector_value == 'Jan':
    df = pd.read_csv('pcl-sales-jan.csv')
    
# if Feb is selected
if month_selector_value == 'Feb':
    df = pd.read_csv('pcl-sales-feb.csv')

shipped = df['Orders Shipped'][ndx]
open = df['Orders Open'][ndx]
info = [shipped, open]

return {
    "data": [go.Pie(labels=["Shipped", "Open"],
                    values=info,
                    textinfo='label')],
    "layout": go.Layout(title=f'Shipped Performance for Selected Day',
                        margin={"l": 300, "r": 300, },
                        legend={"x": 1, "y": 0.7})}

@app.callback(
Output(‘output-selection’, ‘children’),
[Input(‘month-selector’, ‘value’)])

def update_output(value):
chosenmonth = value

print (chosenmonth)

return 'You have selected "{}"'.format(value)

if name == ‘main’:
app.run_server(debug=True,host=‘0.0.0.0’)

The two csv files are below:


Kindest Regards,
Joseph