根据 Python 破折号中的唯一值绘制条形图

Plot Bar Chart based on unique values in Python Dash

我正在尝试在 Python Dash 中嵌入的交互式条形图中可视化不同金融基准(A、X)的加权方案。每个基准由具有不同权重的不同指数组成。切换或取消选择基准时,条形图应相应更改。不知何故,我无法正确调整代码的回调部分,因为我无法创建条形图。有人熟悉这个问题吗?

我正在使用 Jupyter 笔记本。这是我的代码和数据示例:

包和数据:

import pandas as pd
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import plotly.express as px 

data = [['A', 'B', 0.4], ['A', 'C', 0.5], ['A', 'D', 0.1], ['X', 'Y', 0.15], ['X', 'Z', 0.85]]
df = pd.DataFrame(data, columns = ['BM_NAME', 'INDEX_NAME', 'WEIGHT'])
df

条形图。在破折号中,想法是让单个选定基准显示一个条形图(因此 'multi' 设置为 'false'):

barchart = px.bar(
    data_frame=df,
    x="BM_NAME",
    y="WEIGHT",
    color="INDEX_NAME",
    opacity=0.9,
    barmode='group')
barchart

破折号:

# create the Dash app
app = dash.Dash()

# set up app layout
app.layout = html.Div(children=[
    html.H1(children='BM Composition'),
    dcc.Dropdown(id='BM-dropdown',
                options=[{'label': x, 'value': x}
                        for x in df.BM_NAME.unique()],
                 value='A',
                 multi=False, clearable=True),
    dcc.Graph(id='bar-chart')
])


# set up the callback function
@app.callback(
    Output(component_id="bar-chart", component_property="figure"),
    [Input(component_id="BM-dropdown", component_property="value")],
)
def display_BM_composition(selected_BM):
    dff = df.BM_NAME.unique()  # Only use unique values in column "BM_NAME" selected in dropdown

    barchart = px.bar(
        data_frame=df,
        x=filtered_BM,
        y="WEIGHT",
        color="INDEX_NAME",
        opacity=0.9,
        barmode='group')

    return barchart

# Run local server
if __name__ == '__main__':
    app.run_server(debug=True, use_reloader=False)

非常感谢任何帮助或改进建议!

您没有使用回调输入或您创建的更新 dff。试试这个:

def display_BM_composition(selected_BM):
    dff = df.BM_NAME.eq(selected_BM)

    barchart = px.bar(
        data_frame=dff,
        x=filtered_BM,
        y="WEIGHT",
        color="INDEX_NAME",
        opacity=0.9,
        barmode='group')

    return barchart

编辑 经过一番尝试,我找到了以下解决方案,非常适合我:

@app.callback(
    Output(component_id="bar-chart", component_property="figure"),
    [Input(component_id="BM-dropdown", component_property="value")],
)
def display_BM_composition(selected_BM):
    filtered_BM = df[df.BM_NAME == selected_BM]  # Only use unique values in column "BM_NAME" selected in dropdown

    barchart = px.bar(
        data_frame=filtered_BM,
        x="BM_NAME",
        y="WEIGHT",
        color="INDEX_NAME",
        opacity=0.9,
        barmode='group')

    return barchart