简体   繁体   中英

Allow user to sort table in dash (graph objects table)

I have created a dash app in which I am displaying a few tables.

I cannot find how to allow the user to sort the table based on a value. I didn't find anyhting useful on their documentation .

Can I create a custom function where a user can select a column and I can display the data sorted according to that column?

Here's my code for my table:

basic_max_3=go.Figure(data=[go.Table(
    columnwidth=[80, 400,80],
    header=dict(values=list(
        ['col_1', 'col_2','col_3', 'col_4']),
                fill_color=px.colors.qualitative.Pastel2[6],
                align='left'),
    cells=dict(
        values=[df['col_1'], df['col_2'],df['col_3'], df['col_4']],
        fill_color=px.colors.qualitative.Pastel1[8],
        align='left',height=70))], layout=layout_max)

You can use the sort_action attribute of the Table object to enable sorting in your Dash app. The sort_action attribute takes a string value, either 'native' or 'custom'. If you set it to 'native', the table will be sorted using the default sorting behavior of the web browser. If you set it to 'custom', you can specify a custom sorting function using the sort_function attribute.

Here's an example of how you can use these attributes to enable sorting in your table:

import dash
import dash_html_components as html
import dash_table

app = dash.Dash()

df = pd.DataFrame({
    'col_1': [1, 2, 3, 4],
    'col_2': ['A', 'B', 'C', 'D'],
    'col_3': [5, 6, 7, 8],
    'col_4': ['E', 'F', 'G', 'H']
})

app.layout = html.Div([
    dash_table.DataTable(
        id='table',
        columns=[{'name': col, 'id': col} for col in df.columns],
        data=df.to_dict('records'),
        sort_action='custom',
        sort_mode='multi',
        sort_function=sort_function
    )
])

def sort_function(sort_columns, ascending, data_frame):
    # sort the data frame based on the sort_columns and ascending values
    df_sorted = data_frame.sort_values(
        by=sort_columns,
        ascending=ascending
    )
    return df_sorted.to_dict('records')

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

In this example, the sort_function is a custom function that takes three arguments: sort_columns, ascending, and data_frame. The sort_columns argument is a list of column names to sort by, the ascending argument is a list of boolean values indicating whether to sort each column in ascending or descending order, and the data_frame argument is the original data frame.

The sort_function should return the sorted data frame as a list of dictionaries, with each dictionary representing a row in the table.

You can use the updatemenu method to modify the data of the table.

Ie the data frame is sorted according to the selected column and the data in the cells of the table is replaced with this sorted data (see also the intro to dropdowns ).

import pandas as pd 
import numpy as np
import plotly
import plotly.express as px
import plotly.graph_objects as go

# some dummy data
length = 6
data = {
    'col_1': np.random.choice(['cat', 'mouse', 'dog'], length),
    'col_2': np.random.randint(-10, 0, length),
    'col_3': np.random.choice(['a', 'b', 'c', 'd'] , length),
    'col_4': np.random.randint(1, 10, length),
       }
df = pd.DataFrame(data)

# table
basic_max_3=go.Figure(data=[go.Table(
    #columnwidth=[80, 400,80], # didn't fit for dummy data :)
    header=dict(values=list(
        ['col_1', 'col_2','col_3', 'col_4']),
                fill_color=px.colors.qualitative.Pastel2[6],
                align='left'),
    cells=dict(
        values=[df['col_1'], df['col_2'],df['col_3'], df['col_4']],
        fill_color=px.colors.qualitative.Pastel1[8],
        align='left',height=70))]#, layout=layout_max)  # layout_max commented as unknown and not required here
    )
fig = basic_max_3
# drop down to select a column label and sort the data
fig.update_layout(
    updatemenus=[
        {
            # a button for each table column
            'buttons': [
                {
                    'method': 'restyle',
                    'label': btn_label,
                    'args': [
                        {
                            'cells': {
                                'values': df.sort_values(btn_label).T.values,  # update the cell values with the sorted data 
                                # format table as before
                                'fill': dict(color = px.colors.qualitative.Pastel1[8]),
                                'align': 'left',
                                'height': 70
                            }
                        }
                    ],
                }
                for btn_label in ['col_1', 'col_2', 'col_3', 'col_4',]
            ],
            'direction': 'down',
        }
    ]
)

fig.show()

带下拉列表的表格

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM