将颜色渐变应用于 AgGrid 仪表板中的行

问题描述 投票:0回答:1

在下面的代码中,我想根据两列的组合对每行的背景颜色应用颜色渐变:“Raising to Date”和“Years in Operating”(较高的值应导致更深的阴影)颜色)。我想确保此操作是在回调中执行的,并且颜色着色应该基于特定的下拉部分而不是整体数据来工作。

import dash
from dash import dcc, html, Input, Output
import dash_ag_grid as dag
import pandas as pd
import numpy as np

# Example data for the DataFrame 'df'
data = {
    "Company name": ["Company {}".format(i) for i in range(1, n_rows + 1)],
    "Years in Operation": np.random.randint(1, 20, n_rows),
    "Raised to Date": np.random.uniform(1, 100, n_rows).round(2),
    "Product": np.random.choice(["Product A", "Product B", "Product C"], n_rows),
    "Bucket": np.random.choice(["Bucket 1", "Bucket 2", "Bucket 3"], n_rows),
}

df = pd.DataFrame(data)

# Initialize the Dash app
app = dash.Dash(__name__)

# Define the layout
app = dash.Dash(__name__)

# Define the layout
app.layout = html.Div([
    html.H1("Valuation Table"),
    dcc.Dropdown(id='product-dropdown', options=[{'label': 'Product A', 'value': 'Product A'}, {'label': 'Product B', 'value': 'Product B'}], value='Product A'),
    dcc.Dropdown(id='bucket-dropdown', options=[{'label': 'All', 'value': 'All'}, {'label': 'Bucket 1', 'value': 'Bucket 1'}, {'label': 'Bucket 2', 'value': 'Bucket 2'}], value='All'),
    dag.AgGrid(
        id='valuation-table',
        columnDefs=[
            {"headerName": "Company Name", "field": "Company name"},
            {"headerName": "Years in Operation (yr)", "field": "Years in Operation"},
            {"headerName": "Raised to Date ($m)", "field": "Raised to Date"},
            {"headerName": "Product", "field": "Product"},
            {"headerName": "Bucket", "field": "Bucket"},
        ],
        style={'height': '400px', 'width': '100%'},
    ),
    html.Div(id='table-heading')
])

# Callback to update the ag-Grid table
@app.callback(
    [Output('valuation-table', 'rowData'),
     Output('table-heading', 'children')],
    [Input('product-dropdown', 'value'),
     Input('bucket-dropdown', 'value')]
)
def update_table(selected_product, selected_bucket):
    if selected_bucket == 'All':
        filtered_df = df[df['Product'] == selected_product]
    else:
        filtered_df = df[(df['Bucket'] == selected_bucket) & (df['Product'] == selected_product)]

    # Calculate a combined value for color gradient
    filtered_df['Combined Value'] = filtered_df['Raised to Date'] + filtered_df['Years in Operation']
    max_combined_value = filtered_df['Combined Value'].max()

    # Preprocess the DataFrame to include HTML style tags in the cell values
    for col in filtered_df.columns:
        if col != 'Combined Value':
            filtered_df[col] = filtered_df.apply(lambda row: f'<div style="background-color: rgba(0, 123, 255, {row["Combined Value"]/max_combined_value});">{row[col]}</div>', axis=1)

    # Create rowData for ag-Grid
    row_data = filtered_df.to_dict('records')

    return row_data, html.Div(f"Filtered by Product: {selected_product}, Bucket: {selected_bucket}")

if __name__ == '__main__':
    app.run_server(debug=True, port=8573)

问题是我看不到任何颜色

python plotly ag-grid plotly-dash
1个回答
0
投票

问题在于您放入网格中的 HTML 被转义并呈现为文本。实现此目的的另一种方法是通过网格属性应用条件样式

getRowStyle
(请参阅样式化行):

getRowStyle
(字典)单独应用于每行的样式。词典 用钥匙:

  • styleConditions
    (字典列表)。每个字典都有键:
    • condition
      (字符串)决定是否应用
      style
      的 JavaScript 表达式。
    • style
      (字典)。当
      condition
      为 true 时应用的样式属性。
# Callback to update the ag-Grid table
@app.callback(
    [Output('valuation-table', 'rowData'),
     Output('valuation-table', 'getRowStyle'),
     Output('table-heading', 'children')],
    [Input('product-dropdown', 'value'),
     Input('bucket-dropdown', 'value')]
)
def update_table(selected_product, selected_bucket):
    if selected_bucket == 'All':
        filtered_df = df[df['Product'] == selected_product]
    else:
        filtered_df = df[(df['Bucket'] == selected_bucket) & (df['Product'] == selected_product)]

    # Calculate a combined value for color gradient
    filtered_df['Combined Value'] = filtered_df['Raised to Date'] + filtered_df['Years in Operation']
    max_combined_value = filtered_df['Combined Value'].max()

    # Apply conditional row styles according to those combined values
    getRowStyle = {
        'styleConditions': [
            {
                'condition': f'params.data["Combined Value"] == {value}',
                'style': {'backgroundColor': f'rgba(0, 123, 255, {value / max_combined_value}'},
            }
            for value in filtered_df['Combined Value'].unique()
        ]
    }

    # Create rowData for ag-Grid
    row_data = filtered_df.to_dict('records')

    return row_data, getRowStyle, html.Div(f"Filtered by Product: {selected_product}, Bucket: {selected_bucket}")
© www.soinside.com 2019 - 2024. All rights reserved.