Plotly Dash: data_table background color for individual cell
You can define the background color and the font color (as well as several other properties) of each individual cell using style_data_conditional
, see https://dash.plotly.com/datatable/style.
import dash
import dash_table
import dash_html_components as html
import pandas as pd
df = pd.DataFrame(data=dict(COLOR=['#1f77b4', '#d62728', '#e377c2', '#17becf', '#bcbd22'],
VALUE=[1, 2, 3, 4, 5]))
app = dash.Dash(__name__)
app.layout = html.Div([
dash_table.DataTable(
id='table',
columns=[{'name': i, 'id': i} for i in df.columns],
data=df.to_dict('records'),
style_data_conditional=[{'if': {'row_index': i, 'column_id': 'COLOR'}, 'background-color': df['COLOR'][i], 'color': df['COLOR'][i]} for i in range(df.shape[0])]
),
], style=dict(width='100px'))
if __name__ == '__main__':
app.run_server()
Zephyr
Updated on June 05, 2022Comments
-
Zephyr almost 2 years
I display in a
dash_table.DataTable
a dataframe where there is a column with color names in hex format, with this code:import dash import dash_table import pandas as pd df = pd.DataFrame(data = dict(COLOR = ['#1f77b4', '#d62728', '#e377c2', '#17becf', '#bcbd22'], VALUE = [1, 2, 3, 4, 5])) app = dash.Dash(__name__) app.layout = html.Div([dash_table.DataTable(id = 'table', columns = [{"name": i, "id": i} for i in df.columns], data = df.to_dict('records'))], style = dict(width = '200px')) if __name__ == '__main__': app.run_server()
This is what I get:
I would like to set the background color (and maybe the font color) of each individual cell with its content, but only for that column (which is always the first column of the table) in order to get this:
To me is ok to replace the
dash_table.DataTable
withplotly.graph_objects.Table
(documentation), which maybe it is more customizable; provided that I can implement theplotly.graph_objects.Table
in adash
dashboard.Version info:
Python 3.7.0 dash 1.12.0 dash-table 4.7.0 plotly 4.7.0
-
Zephyr almost 4 yearsYou are very close, I updated the question to be more precise: it is necessary that it is colored only the background of that column (which is always the first column) and not the rest of the table. I think a small change to the code you added is enough
-
Zephyr almost 4 yearsThat's exactly want I want, fantastic!