Search code examples
pythonplotlyplotly-python

Can't update plotly go.Table column order and cell color using dropdown buttons


I have two pandas dataframes, scores containing a set of scores I would like to display in a table, and colours mapping a set of colours I would like the cells in the table to be. Both share the same column headers and index.

I am trying to generate a dropdown menu for a table created in plotly using go.Table. Without dropdown options I am able to set up a table with cells coloured according to their value in the following way:

    table = go.Figure(data=[go.Table(
    header=dict(values= scores_cols,
                fill_color='paleturquoise',
                align='center'),
    cells=dict(values= [scores[x] for x in scores_cols],
            fill_color=[colours[x] for x in scores_cols],
            align='center'))
            ])

In order to add dropdown buttons to sort columns and their corresponding cell colours I am using the following:

buttons = []

for score in scores_cols:
    scores = scores.sort_values(by = [score])
    colours = colours.reindex(scores.index)
    buttons.append(dict(
           label = score,
           method = 'restyle',
           args = [
                    {"cells": 
                        {"values": [scores[x] for x in scores_cols],
                        "fill_color": [colours[x] for x in scores_cols]},
                    }]))
table.update_layout(
    updatemenus=[
        dict(
            buttons=buttons,
            direction="down",
            pad={"r": 10, "t": 10},
            showactive=True,
            x = 0.01,
            y = 1.3,
            xanchor="left",
            yanchor="top")
            ])

The colour mapping works for the initial table, however when a dropdown button is clicked, the table is updated to reflect the new row ordering according to the selected column, but no colour mapping is present at all. Any advice with this would be great as I am running out of ideas !


Solution

  • Found the answer to this. When updating the fill colour, a dict of params for the fill should be passed with fill as one of them, rather than trying to directly assign fill_color:

        buttons.append(dict(
                label = score,
                method = 'restyle',
                args = [
                    {"cells": {
                        "values": [sorted_scores[x] for x in displayed_scores_cols], 
                        "fill": dict(color = [sorted_colours[x] for x in displayed_scores_cols])}}]))