动态数据框和Dash回调中的条件样式化

huangapple go评论105阅读模式
英文:

Dynamic dataframe and conditional styling in dash callbacks

问题

我是新手,尝试为我的数据表格(DashTable)添加样式,使得与同一列第一行中的单元格值不同的每个单元格都会突出显示。因为我需要在Kubernetes上部署Dash,还有一些与路径相关的原因,我将Dash应用程序作为一个具有多个Input/Output回调的类(我知道我也不喜欢它)。我正在尝试为每个回调动态生成的数据帧添加样式。

注意代码不完整,但函数的返回值是正确的,它创建了一个字典列表。当我添加代码中的for循环部分时,我的表格没有更新。但仅使用selected_row_style来突出显示选定行时,它可以更新。非常感谢任何帮助。此外,代码没有缩进问题。

英文:

I am new to dash and trying to style my dashtable so that every cell with a different value from the cell in the same column in the first row gets highlighted. Because I need to deploy dash in Kubernetes and other reasons that have to do with paths I have the dashapp as a class with a giant multiple Input/Output callback. ( I know I don't like it either) I am trying to style a dataframe that is dynamically generated for every callback.

  1. html.Div(
  2. className="eight columns div-for-charts bg-grey",
  3. children=[
  4. dcc.Graph(id="graph"),
  5. html.Div(
  6. className="text-padding",
  7. children=[
  8. "You can filter the table columns by clicking on the column name.",
  9. ],
  10. ),
  11. dash_table.DataTable(
  12. id='datatable-interactivity',
  13. columns=[
  14. {"name": i, "id": i, "deletable": False, "selectable": True} for i in
  15. self.predictions.columns
  16. ],
  17. # make header font black
  18. style_header={'color': 'black', 'backgroundColor': 'white'},
  19. style_data={'color': 'black', 'backgroundColor': 'white'},
  20. data=self.predictions.to_dict('records'),
  21. editable=False,
  22. filter_action="native",
  23. sort_mode="multi",
  24. column_selectable="single",
  25. row_selectable="multi",
  26. row_deletable=True,
  27. selected_columns=[],
  28. selected_rows=[],
  29. page_action="native",
  30. page_current=0,
  31. page_size=20,
  32. style_table={'overflowX': 'scroll'},
  33. ),
  34. ],
  35. ),
  36. def start_callback(self):
  37. @self.multiple_callbacks.callback(
  38. [dash.dependencies.Output("graph", "figure"),
  39. dash.dependencies.Output(component_id="datatable-interactivity", component_property='data'),
  40. dash.dependencies.Output("datatable-interactivity", "style_data_conditional")],
  41. [dash.dependencies.Input(component_id='algorithm_dd', component_property='value'),
  42. dash.dependencies.Input(component_id="graph", component_property="selectedData"),
  43. dash.dependencies.Input(component_id='value_slider', component_property='value'),
  44. dash.dependencies.Input(component_id='checklist', component_property='value'),
  45. dash.dependencies.Input(component_id="datatable-interactivity", component_property="active_cell"),
  46. ])
  47. if len(selectedData['points']) == 1:
  48. key = selectedData['points'][:]
  49. a = key[0]['hovertext']
  50. df_f = self.get_nearest_neighbours(self.predictions, hovertexts[0], value_slider, alg_name)
  51. selected_row_style =[{"if": {"filter_query": "{{apk_name}} ={}".format(a)}, "backgroundColor": "yellow", }]
  52. cell_styles = []
  53. for column in df_f.columns:
  54. cell_styles.append({
  55. 'if': {
  56. 'column_id': column,
  57. 'filter_query': f'{{{column}}} != {df_f[column].iloc[0]}',
  58. },
  59. 'backgroundColor': 'pink',
  60. 'color': 'white',
  61. })
  62. selected_row_style.extend(cell_styles)
  63. return plot_fig_selected, df_f.to_dict('records'), selected_row_style

Notice how the code is not complete, but the return values of the function are correct and it creates a list of dictionaries. Somehow my table does not update when I add the for loop part in the code. It does update with only the selected_row_style with the yellow highlighting for the selected row though. Any help is much appreciated. Also there is no indent problem on the code.

答案1

得分: 1

由于您的代码尚未完成,并且不是可复制的示例,请参考以下代码来修改您的代码:

  1. import pandas as pd
  2. import dash_table
  3. import dash
  4. import dash_html_components as html
  5. import dash_core_components as dcc
  6. import dash_bootstrap_components as dbc
  7. df = pd.DataFrame({'num': [1, 2, 1, 3, 1, 5, 1]})
  8. df['matches?'] = df['num'].shift(1) != df['num']
  9. df['matches?'] = df['matches?'].astype(str)
  10. app = dash.Dash(__name__, external_stylesheets=[dbc.themes.LUX])
  11. app.layout = dash_table.DataTable(
  12. data=df.to_dict('records'),
  13. columns=[{'name': i, 'id': i} for i in df.columns[0:1]],
  14. style_data_conditional=[
  15. {'if': {'filter_query': '{matches?} eq "True"', 'column_id': 'num'},
  16. 'color': 'black', 'backgroundColor': 'white'
  17. },
  18. {'if': {'filter_query': '{matches?} eq "False"', 'column_id': 'num'},
  19. 'color': 'white', 'backgroundColor': 'green'
  20. }
  21. ]
  22. )
  23. if __name__ == '__main__':
  24. app.run_server(debug=False, port=1213)

如您所见,我们需要首先使用shift找到不同的单元格,然后将其用于dash_table的条件格式化。

英文:

Because of your code still not finish and it's not reproductive sample so please refer below code to revise yours.

  1. import pandas as pd
  2. import dash_table
  3. import dash
  4. import dash_html_components as html
  5. import dash_core_components as dcc
  6. import dash_bootstrap_components as dbc
  7. df = pd.DataFrame({'num': [1, 2, 1, 3, 1, 5, 1]})
  8. df['matches?'] = df['num'].shift(0)==df['num'].loc[0]
  9. df['matches?'] = df['matches?'].astype(str)
  10. app = dash.Dash(__name__, external_stylesheets=[dbc.themes.LUX])
  11. #print(df)
  12. app.layout = dash_table.DataTable(
  13. data=df.to_dict('records'),
  14. #sort_action='native',
  15. columns=[{'name': i, 'id': i} for i in df.columns[0:1]],
  16. style_data_conditional=[
  17. {'if': {'filter_query': '{matches?} eq "False"',
  18. 'column_id': 'num'
  19. },
  20. 'color': 'white','backgroundColor':'green'
  21. },
  22. {'if': {'filter_query': '{matches?} eq "True"',
  23. 'column_id': 'num'
  24. },
  25. 'color': 'black','backgroundColor':'white'
  26. },
  27. ]
  28. )
  29. if __name__ == '__main__':
  30. app.run_server(debug=False, port=1213)

As you see we need to find the different cell first by using shift then use this to conditional_formating dash_table.

动态数据框和Dash回调中的条件样式化

huangapple
  • 本文由 发表于 2023年3月15日 17:41:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75742904.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定