如何在 Dash-Plotly 中包含基于条件的跟踪

How to include the trace based on condition in Dash-Plotly

我有多个跟踪的堆叠图(优先级高、低),请求数据来自 CSV 文件,它可能有也可能没有优先级(比如高)。我将跟踪添加到图表中,但如果我们没有在 CSV 中获得高优先级请求,它会抛出异常。

figure_priority={
           'data': [
                    trace2,
                     trace1,

我所做的是条件检查以验证数据帧中是否存在优先级,然后返回相关数字,即

if High in Col.list && Low in Col.list: 
  trace2 = go.Bar(x=pv.index, y=pv[('Number', 'High')]
  trace1 = go.Bar(x=pv.index, y=pv[('Number', 'Low')]
                 figure_priority={
                'data': [
                
                    trace2,
                     trace1,
elif Low in Col.list :
trace = go.Bar(x=pv.index, y=pv[('Number', 'Low')]
          figure_priority={
                'data': [
                    trace2,

但我认为会有更简单的方法来执行此逻辑,当我获得高、低和中优先级时会发生什么 我如何检查特定组是否在列中并根据内容向堆叠图表添加跟踪..

您可以使用 for 循环并填写跟踪列表:

types = ['High', 'Medium', 'Low']
traces = []
for type in types:
    if type in Col.list:
        traces.append(go.Bar(x=pv.index, y=pv[('Number', type)])

如上所述,这里是堆叠条带颜色的代码片段,欢迎任何优化..

        app_type=[('High','#7a5195'),('Low','#ffa600'),('Medium','#ffa6CC')]
        traces =[]
        for app_type,color in app_types:
            if app_type in str(pv.columns.tolist())
                traces.append(
                    go.Bar(x=pv.index, y=pv[('Number', app_type)], text=pv[('Number', app_type)], textposition = 'auto',
                            opacity=0.8,
                            marker={"color":color,
                            "line": {
                                "color": "#cdcdcd",
                                "width": 2,
                            },
                    },            
                        name=app_type)
                )

        figure_new={
                "data":
                    traces
                ,
                 'layout': go.Layout(