Plotting different charts(graphs) from a drop down

Hi, I am new to dash and i have been struggliing for two days to design something.
I have been able to follow the documentation and upload a file, then visualize it(plot a grap - bar graph to be specific). But the challenge i have is i want to be able to create a drop-down or radio button having multiple chart-types, say a bar graph, and a scatter plot. so i can juust choose from one of them and a graph is displayed.
Please i request your assistance. Thank you

Hi John,

You can use a callback to return different figure types based on a user selection. In the example below I’m just using a simple dataframe to demonstrate. Based on the user selection I create either a bar graph or scatter plot with the same data. The choose_graph_type() function looks at what value is selected in the dropdown and constructs the appropriate figure. Basic callback documentation. Hope this helps.

import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px

app = dash.Dash(__name__)

data = pd.DataFrame({
    'Column 1' : [1,2,3,4,5],
    'Column 2' : [2,4,8,16,32]
})

app.layout =html.Div([
    dcc.Dropdown(
        id = 'graph-type',
        placeholder='Select graph type',
        options= [
            {'label' : 'scatter', 'value' : 'scatter'},
            {'label' : 'bar', 'value' : 'bar'}
        ]
    ),
    dcc.Graph(
        id='graph'
    )
])

@app.callback(
    Output('graph', 'figure'),
    [Input('graph-type', 'value')]
)
def choose_graph_type(graph_type):
    if graph_type is None:
        raise dash.exceptions.PreventUpdate()
    if graph_type == 'scatter':
        return px.scatter(data, x='Column 1', y='Column 2')
    elif graph_type == 'bar':
        return px.bar(data, x='Column 1', y='Column 2')
    return None

if __name__ == '__main__':
    app.run_server(debug=True)
1 Like

Thank you @Jwolf
This really helped. I was fighting with the callback functionality.

I had one more thing i was thinking of.
Is it possible that the graph is only shown when a selection is made - than having an empty graph displayed waiting for inputs ?

So for instance, The graph area is hidden until i select a particular graph to be plotted then it appears. I find it weird that a graph is appearing with no data…