The "filter_query": "{{id}} = {}".format(i)
is the magic that applies the color to each row.
The “if” statement is selecting the column “Humidity” and the filter_query is selecting the row.
It’s necessary to have a column called “id” which contains a row id. The example adds the “id” column like this:
df["id"] = df.index
If you add this to your dataframe, it will probably work. If it doesn’t, check that the index is like the default index (0,1,2,3…) otherwise the enumerate() wont’ work right. If you do other filtering and sorting, reset the index first like this:
# df sort or filter....
df=df.reset_index(drop=True)
df["id"] = df.index
More info on row id’s here: https://dash.plotly.com/datatable/interactivity
BTW, here’s a simpler way that might work for you…
Since it looks like you are assigning a discrete color to cell value, you could make a dictionary. No need to mess with row id’s:
import dash
import dash_table
import pandas as pd
data = dict(
[
("Date", ["2015-01-01", "2015-10-24", "2016-05-10", "2017-01-10", "2018-05-10", "2018-08-15"]),
("Region", ["Montreal", "Toronto", "New York City", "Miami", "San Francisco", "London"]),
("Temperature", [1, -20, 3.512, 4, 10423, -441.2]),
("Humidity", [10, 20, 30, 40, 50, 60]),
("Pressure", [2, 10924, 3912, -10, 3591.2, 15]),
]
)
df = pd.DataFrame(data)
# keys are the "Humidity" data
colors = {
10: "#c54040",
20: "#c58d36",
30: "#65c336",
40: "#32c1be",
50: "#483dbe",
60: "#000000",
}
app = dash.Dash(__name__)
app.layout = dash_table.DataTable(
data=df.to_dict("records"),
columns=[{"name": i, "id": i} for i in df.columns],
style_data_conditional=[
{
"if": {
"column_id": "Humidity",
"filter_query": "{{Humidity}} = {}".format(i),
},
"backgroundColor": colors[i],
"color": "white",
}
for i in colors
],
)
if __name__ == "__main__":
app.run_server(debug=True)