Reputation: 81
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)
Upvotes: 3
Views: 979
Reputation: 2136
You can use the updatemenu method to modify the data of the table.
I.e. 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()
Upvotes: 3