Filtering options for plotly dashboard in dropdown format

Below is a dataset along with code that generates a chart:

Column A Tools Category role figure Occurences After idx
0 PostgreSQL DatabaseHaveWorkedWith Developer, front-end 38.044286 4 False
1 MySQL DatabaseHaveWorkedWith Developer, front-end 45.883489 2 False
0 MongoDB DatabaseWantToWorkWith Developer, front-end 39.018110 1 True
1 PostgreSQL DatabaseWantToWorkWith Developer, front-end 48.236203 3 False
0 MySQL DatabaseHaveWorkedWith Developer, back-end 26.096002 1 True
1 PostgreSQL DatabaseHaveWorkedWith Developer, back-end 33.771734 2 False
0 Redis DatabaseWantToWorkWith Developer, back-end 28.495408 1 True
1 PostgreSQL DatabaseWantToWorkWith Developer, back-end 40.314136 1 True
from itertools import cycle
import plotly.express as px
fig = go.Figure()

palette = cycle(px.colors.qualitative.Alphabet)
colors = {c:next(palette) for c in daata['Tools'].values}
#Build dropdown Labels
labels = daata['role'].unique()

for i, row in daata.iterrows():
    fig.add_trace(
        go.Bar(x=[[row['role']],[row["Category"]]],
            y=[row["figure"]],
            name=row["Tools"],
            text=str(round(row["figure"],2))+'%', showlegend=row['idx'],marker_color=colors[row["Tools"]],
            legendgroup=row["Tools"]# Fix legend
            ))

fig.update_layout({
   'barmode': 'group',
    'xaxis': {
        'tickangle': -45,
    },
    'yaxis': {
        'title_text': "figures",
    },
})
fig.show()

The provided code results in the chart displayed here

Adding a dropdown filter for roles is desired (e.g., filtering by 'Developer, back-end', 'Developer, front-end' and 'All')

Attempts to add button labels have not been successful in correctly filtering the chart.

Answer №1

Utilize the functionality of dash to implement a Dropdown menu and retrieve relevant data. Refer to the code snippet below for guidance:

from dash import Dash, dcc, html, dash_table, Input, Output, callback
import plotly.express as px
import dash_bootstrap_components as dbc
import pandas as pd
from itertools import cycle

palette = cycle(px.colors.qualitative.Alphabet)
colors = {c:next(palette) for c in daata['Tools'].values}
#Build dropdown Labels
labels = daata['role'].unique()
app = Dash(__name__, external_stylesheets=[dbc.themes.LUX])
app.layout = html.Div([
     dcc.Dropdown(id='dropdown',
                  options=[
                      {'label': x, 'value': x} for x in df['role'].unique()],
                         value=[],
                         multi=True,
                         disabled=False,
                         clearable=True,
                         searchable=True),
    dcc.Graph(id='graph',figure={})
])

@app.callback(Output('graph','figure'),
              Input('dropdown','value'))
def update_graph(role):
    if role == []:
        dff= daata.copy()
        fig = go.Figure()
        for i, row in dff.iterrows():
            fig.add_trace(
            go.Bar(x=[[row['role']],[row["Category"]]],
            y=[row["figure"]],
            name=row["Tools"],
            text=str(round(row["figure"],2))+'%', showlegend=row['idx'],marker_color=colors[row["Tools"]],
            legendgroup=row["Tools"]# Fix legend
            ))

            fig.update_layout({
                'barmode': 'group',
                'xaxis': {'tickangle': -45},
                'yaxis': {'title_text': "figures",},
            })
    else:
        dff= daata[daata['role'].isin(role)]
        fig = go.Figure()
        for i, row in dff.iterrows():
            fig.add_trace(
            go.Bar(x=[[row['role']],[row["Category"]]],
            y=[row["figure"]],
            name=row["Tools"],
            text=str(round(row["figure"],2))+'%', showlegend=row['idx'],marker_color=colors[row["Tools"]],
            legendgroup=row["Tools"]# Fix legend
            ))

            fig.update_layout({
                'barmode': 'group',
                'xaxis': {'tickangle': -45},
                'yaxis': {'title_text': "figures",},
            })
    return fig

if __name__ == "__main__":
    app.run_server(debug=False)

For visuals on the implementation, you can refer https://i.stack.imgur.com/rbRhS.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to maintain a cumulative sum for a variable in Python?

I'm struggling to make the take_input function increment the total every time it's called. The problem is that I can't seem to get the daily_expense variable to accumulate when an expense is added more than once. def take_input(): daily_ ...

Optimal method for shuffling a matrix in either R or Python

Currently, I am dealing with a large numeric matrix M in R that consists of 11000 rows and 20 columns. Within this matrix, I am conducting numerous correlation tests. Specifically, I am using the function cor.test(M[i,], M[j,], method='spearman' ...

Exploring data in view - Django template

As a newcomer to the world of Python and Django, I am seeking guidance on how to access dictionary variables within a template. Despite attempting various methods, none have proven successful thus far. Upon printing the variable received from my view funct ...

The JSON data was retrieved in a different order compared to the text data during scraping

Attempting to retrieve data from www.crunchbase.com through their API, I created a basic Python script for fetching responses. However, when writing the json_data to a file, I noticed that the order of the keys does not match the response order obtained di ...

Discover the dictionary key linked to a specific value in Python

My task is to look up the value of two elements in a dictionary rather than their key. The code I currently have does not search for the value of the dictionary: for key in val["timeSlot"]: for value in val[key]: if test_date in value: ...

Encountering a Problem with Github Actions: Exit Code 2 Detected

I need help with the following code snippet for setting up Github Actions: name: Python application on: push: branches: [ main ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Install dep ...

Error! The function worker.recognize(...).progress is throwing an error. Any ideas on how to resolve this

Here is the code snippet: //Imports const express = require('express'); const app = express(); const fs = require("fs"); const multer = require('multer'); const { createWorker } = require("tesseract.js"); co ...

Tips for showing the chosen value of a ModelChoiceField in Django

Is there a way to display only the selected value from a forms.ModelChoiceField on a view page? I'm struggling to find a clear solution as a Python newbie, despite searching through various forums. Here is the form code snippet: class Manufacturer1F ...

Selenium error: Unable to click on element at specified coordinates (x, y)

On my website , I am trying to automate the process of inserting a number into the PAGE field and clicking GO using a script. However, I am encountering an error: File "/Users/anhvangiang/Desktop/PY/inc.py", line 34, in scrape driver.find_element_by_xpath ...

What is the best way to read JSON responses from a Unirest request in Python?

response_post =unirest.get("http://timesofindia.indiatimes.com/feeds/newsdefaultfeeds.cms?feedtype=sjson",headers={ "X-Mashape-Key": "key", "Accept": "application/json"},) What is the best way to convert the response_post into a JSON result? ...

Can you explain the distinction between a threaded and a non-threaded Win10Toast notification within a Python context?

Exploring the win10toast documentation reveals two examples of notifications: from win10toast import ToastNotifier toaster = ToastNotifier() toaster.show_toast("Greetings Earthlings!", "Python is simply splendid in 10 seconds!", icon_path="custom ...

Tips for creating a Numpy array filled with lists

I'm attempting to generate a numpy array that resembles array([[list([]), list([])], [list([]), list([])], [list([]), list([])]], dtype=object) This specific array is of shape (3,2). However, each time I try np.array([[list(), list() ...

What could be causing Python to return a None value after performing a calculation?

Recently, I needed a tool to generate a multiplication table, so I came up with the following code: def createMultiplicationTable(num): for i in range(1, 11): result = num * i print(f'{num} X {i} = {result}') table = createM ...

A simple guide on logging into Discord with token using the Selenium library in Python

I created a Python code using the selenium module to log in to Discord using a token number. The token number needs to be added to localStorage, so I used JavaScript code to add it successfully. However, upon checking Application -> localStorage -> https:/ ...

Retrieving a JavaScript variable's value in Selenium with Python

rwdata = driver.find_elements_by_xpath( "/html/body/div[2]/div/div/div/form[2]/div[2]/table/tbody") This table contains the value of variable r as text/javascript type. for r in rwdata: print(r.text) if r.text != "Booked": ...

Engaging with website components that modify HTML content values

I'm using Selenium to automate the process of clicking through parking garage markers on the website http://seattle.bestparking.com/. The goal is to open the pop-up info window for each marker and then extract information from the "rate" page in the p ...

Tips for transforming a pandas dataframe into a dictionary that can be sliced

My pandas data frame df is structured as follows: import pandas as pd data = [[1, 'Jack', 'A'], [1, 'Jamie', 'A'], [1, 'Mo', 'B'], [1, 'Tammy', 'A'], [2, 'JJ', ' ...

Is there a way to apply a uniform value to all channels of a 3-channel image?

Currently, I am working with an image processing task: img = cv2.imread("sky.png", 1) In my process, I aim to add a pixel in each column for every channel. My approach involves the following steps: img[row_1, :, 0] = np.insert(img[row_1,:,0], column_1, ...

The error message "cv2 module not found while exporting Anaconda path" appeared when

Running ubuntu 14.04, I successfully installed OpenCV3. Later on, I added anaconda (python) to the mix. In order to get everything working smoothly, I was instructed to edit ~/.bashrc and export the anaconda path there. Switching to python 2.7.8 resulted ...

Error: The object with the memory address 0x7f3f4bd01470 returned by the neo4j.work.result.Result is not compatible with JSON serialization

Hello, I am facing an error with the following code and need assistance in resolving it: class GenerateQuery: @staticmethod def get_nlg(graph_query): # graph = Graph("http://localhost:7474",auth=("neo4j", "pass" ...