Learn how to use Dash Bio for next-gen sequencing & quality control. 🧬 Register for the Oct 27 webinar.

Can't create a simple bar chart in Dash

I’m new to Dash and I’ve been trying to create a simple barchart with a dropdown being the column names in a dataframe. The bar chart that it is supposed to create is a frequency table using pd.crosstab, based on the dropdown selected. The error I’m getting is

Invalid argument figure.data passed into Graph with ID “freq_graph”.
Expected an array.
Was supplied type object.

Below is my code below. would appreciate any guidance.

import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from dash.dependencies import Input, Output

df = pd.read_csv(‘data.csv’)

df_cols = df.columns.to_list()

app = dash.Dash()

all_columns =
for i in df_cols:
all_columns.append({‘label’:i, ‘value’:i})

app.layout = html.Div([
dcc.Graph(id = ‘freq_graph’),
dcc.Dropdown(id = ‘column_pick’,
options = all_columns,
value = ‘STATE’)
])

@app.callback(
Output(‘freq_graph’, ‘figure’),
[Input(‘column_pick’, ‘value’)])

def update_fig(selected_column):
filtered_df = pd.crosstab(df[selected_column], columns=‘count’).reset_index()
traces = go.Bar(
x=filtered_df[selected_column],
y=filtered_df[‘count’]
)

return {
    'data': traces,
    'layout': go.Layout(xaxis={'groupings'}
    )
}

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

Hey @semidevil, and welcome to Dash.

Here’s an MWE for how I got this to work for you: https://gist.github.com/chrisvoncsefalvay/8be2c3fb4005afe9c1fbbfb811f163a8

To explain a little bit: good practice is to have a function that creates a plot based on data (create_fig) dependent on the parameters, and then the callback only passes parameters in and gets the results out. A callback alone is not enough, and should generally just invoke the primary plotting function. This is important because callbacks are triggered on change. There’s no change to speak of at rendering time, so you should be able to invoke your rendering function (create_fig) from your layout before any callbacks happen.

I hope this helps. Please let me know if there’s anything else you need assistance with.