Skip to content

How to Order Filter Options According to Predefined Categorical Sequence in Vizro #1049

@fpeucelle

Description

@fpeucelle

Question

Dear Vizro Team,

I hope this message finds you well. I am currently working on a dashboard and have encountered a challenge regarding the ordering of filter options. Specifically, I aim to have a filter display its options according to a predefined categorical order, rather than the default alphabetical arrangement.

Context:

In my dataset, the 'Circunscripción' column is defined as an ordered categorical variable with a specific sequence. However, when implementing a filter for this column in Vizro, the options appear alphabetically instead of following the intended order.

Issue:

Despite defining the 'Circunscripción' column as an ordered categorical variable, the filter options are displayed alphabetically.

Request:

Could you please advise on how to configure the filter in Vizro to display options according to the predefined categorical order? Any guidance or recommendations would be greatly appreciated.

Thank you very much for your assistance.

Best regards, Francisco

Image

Code/Examples

import pandas as pd
from vizro import Vizro
import vizro.plotly.express as px
import vizro.models as vm

# Define the order of the districts directly in the code
orden_circunscripciones = ["Total", "Trelew", "Comodoro Rivadavia", "Esquel", "Puerto Madryn", "Rawson", "Sarmiento"]

# Create example DataFrame
data = {
    "año": [2012, 2012, 2012, 2012],
    "Circunscripción": ["Esquel", "Trelew", "Rawson", "Total"],
    "Casos": [1, 3, 2, 6]
}
df = pd.DataFrame(data)

# Convert "Circunscripción" to an ordered categorical type
df["Circunscripción"] = pd.Categorical(
    df["Circunscripción"],
    categories=orden_circunscripciones,  # Order defined in the code
    ordered=True
)

# Sort the DataFrame respecting the defined order
df = df.sort_values(by="Circunscripción")

# Create the bar chart
figura = px.bar(df, x="Circunscripción", y="Casos", title="Cases by District")

# Create the graph component
grafico = vm.Graph(figure=figura)

# Create the page containing the graph with a filter
pagina = vm.Page(
    title='Bar Chart of Cases by District',
    components=[grafico],
    controls=[
        vm.Filter(column="Circunscripción", selector=vm.RadioItems())
    ],
)

# Create the dashboard with the page
dashboard = vm.Dashboard(pages=[pagina])

# Run the dashboard
Vizro().build(dashboard).run()

Which package?

vizro

Code of Conduct

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions