Plotly 图表不尊重数据

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

当我尝试使用 Plotly 生成图表时遇到两个问题。第一:所有柱形图都具有相同的值,并且不尊重“data”变量中传递的值。其次,我想更改条形标签“.”的分隔符。到“,”。

这是代码:

import plotly.graph_objects as go
import plotly.io as pio

data = [
    ['FT-Transformer', 0.8102, 'MLP', 0.7790, 'TabNet', 0.7904, 'TabTransform', 0.7960, 'FT-Transformer', 0.7989, 'TabNet', 0.8073],
    ['TabNet', 0.8101, 'TabNet', 0.7592, 'NODE', 0.7790, 'NODE', 0.7847, 'NODE', 0.7904, 'NODE', 0.7818],
    ['NODE', 0.7989, 'NODE', 0.7535, 'TabTransform', 0.7677, 'TabNet', 0.7818, 'MLP', 0.7904, 'FT-Transformer', 0.7790],
    ['MLP', 0.7932, 'FT-Transformer', 0.7375, 'MLP', 0.6742, 'FT-Transformer', 0.7648, 'TabNet', 0.7705, 'TabTransform', 0.7592],
    ['TabTransform', 0.7705, '1D-CNN', 0.7365, '1D-CNN', 0.6685, 'MLP', 0.7082, 'TabTransform', 0.7677, 'MLP', 0.7535],
    ['1D-CNN', 0.6799, 'TabTransform', 0.7337, 'FT-Transformer', 0.5864, '1D-CNN', 0.5609, '1D-CNN', 0.7025, '1D-CNN', 0.7082]
]

strategies = ['TA/HI', 'PCA', 'SA', 'UNDER', 'OVER', 'AUMENTADO']


architectures = ['1D-CNN', 'FT-Transformer', 'MLP', 'NODE', 'TabNet', 'TabTransform']

colors = {
    '1D-CNN': '#1f77b4',        # Azul
    'FT-Transformer': '#ff7f0e', # Laranja
    'MLP': '#2ca02c',            # Verde
    'NODE': '#9467bd',           # Roxo
    'TabNet': '#8c564b',         # Marrom
    'TabTransform': '#d62728'    # Vermelho
}


fig = go.Figure()

for i in range(len(architectures)):
    y_values = []
    text_values = []
    color_values = []
    for j in range(len(strategies)):
        strategy = strategies[j]
        found = False
        for k in range(len(data)):
            for l in range(0, len(data[k]), 2):
                if data[k][l] == architectures[i] and data[k][l+1] > 0:
                    y_values.append(data[k][l+1])
                    text_values.append("<b>{:.2%}</b>".format(data[k][l+1]))
                    color_values.append(colors[architectures[i]])
                    found = True
                    break
            if found:
                break
        if not found:
            y_values.append(0)
            text_values.append("<b>0.00%</b>")
            color_values.append(colors[architectures[i]])

    fig.add_trace(go.Bar(
        name=architectures[i],
        x=strategies,
        y=y_values,
        text=text_values,
        textposition="outside",
        textangle=0,
        textfont=dict(size=10),
        marker=dict(color=color_values)
    ))

fig.update_layout(
    font=dict(size=12),
    plot_bgcolor='rgba(0,0,0,0)',
    barmode='group',
    bargap=0.1,
    bargroupgap=0.05,
    legend=dict(orientation='h', yanchor='bottom', y=1.02, xanchor='center', x=0.5),
    margin=dict(t=200)
)

def format_percent(value):
    return "{:.2f}%".format(value).replace('.', ',')

for annotation in fig.layout.annotations:
    annotation.text = format_percent(float(annotation.text))

fig.update_layout(yaxis_tickformat='.2%', separators=',')

fig.show()

我已经尝试了几种解决方案,但是,我仍然无法生成所需的图表,该图表由多个条形图组成,每个策略一个。有人可以帮助我吗?

python plotly
2个回答
1
投票

我不完全理解您问题中的数据如何与字符串列表和多个列表相关,但我已经处理了数据,并理解您的数据将名为策略的字符串列表表示为列,将多个列表表示为行,然后创建了图表。数据处理在数据框中以便于以后处理。该图是在新创建的数据框中按体系结构名称提取的数据框中绘制的。接下来,通过在文本注释中将其替换为逗号,将百分比中的小数点更改为逗号。

import numpy as np

data = np.array(data)
df = pd.DataFrame()

for i,s in zip(np.arange(0,data.shape[0],1), strategies):
    #print(np.array(data[:,i*2]))
    #print(np.array(data[:,i*2+1]))
    df_tmp = pd.DataFrame({'strategies': s, 'architectures': data[:,i*2], 'per': data[:,i*2+1]})
    df_tmp['per'] = df_tmp['per'].astype(float)
    df = pd.concat([df, df_tmp])

fig1  = go.Figure()

for i,a in enumerate(architectures):
    dff = df.query('architectures == @a')
    fig1.add_trace(go.Bar(
        x=dff['strategies'],
        y=dff['per'],
        name=architectures[i],
        text=[str(x).replace('.', ',') for x in dff['per']],
        textposition="outside",
        textangle=0,
        textfont=dict(size=10),
        marker=dict(color=[colors[c] for c in dff['architectures'].values]),
    ))
fig1.layout.height=500
fig1.update_layout(font=dict(size=12),
                   plot_bgcolor='rgba(0,0,0,0)',
                   barmode='group',
                   bargap=0.1,
                   bargroupgap=0.05,
                   legend=dict(orientation='h', yanchor='bottom', y=1.02, xanchor='center', x=0.5),
                   margin=dict(t=200)
                  )

   
fig1.update_layout(yaxis_tickformat='.2%', separators=',')
fig1.show()


0
投票

您的代码中存在多个问题,首先您应该为您的数据使用

dictionary
,您的
break
被误用了被误用了,您使用的格式是错误的,您需要向
d3-format提供一个
tickformat
说明符字符串
yaxis

这是我更改您的代码的方法:

import plotly.graph_objects as go

architectures = ['1D-CNN', 'FT-Transformer', 'MLP', 'NODE', 'TabNet', 'TabTransform']
strategies = ['TA/HI', 'PCA', 'SA', 'UNDER', 'OVER', 'AUMENTADO']

data = {
    'TA/HI': [('FT-Transformer', 0.8102), ('MLP', 0.7790), ('TabNet', 0.7904), ('TabTransform', 0.7960), ('FT-Transformer', 0.7989), ('TabNet', 0.8073)],
    'PCA': [('TabNet', 0.8101), ('TabNet', 0.7592), ('NODE', 0.7790), ('NODE', 0.7847), ('NODE', 0.7904), ('NODE', 0.7818)],
    'SA': [('NODE', 0.7989), ('NODE', 0.7535), ('TabTransform', 0.7677), ('TabNet', 0.7818), ('MLP', 0.7904), ('FT-Transformer', 0.7790)],
    'UNDER': [('MLP', 0.7932), ('FT-Transformer', 0.7375), ('MLP', 0.6742), ('FT-Transformer', 0.7648), ('TabNet', 0.7705), ('TabTransform', 0.7592)],
    'OVER': [('TabTransform', 0.7705), ('1D-CNN', 0.7365), ('1D-CNN', 0.6685), ('MLP', 0.7082), ('TabTransform', 0.7677), ('MLP', 0.7535)],
    'AUMENTADO': [('1D-CNN', 0.6799), ('TabTransform', 0.7337), ('FT-Transformer', 0.5864), ('1D-CNN', 0.5609), ('1D-CNN', 0.7025), ('1D-CNN', 0.7082)]
}

colors = {
    '1D-CNN': '#1f77b4',        # Azul
    'FT-Transformer': '#ff7f0e', # Laranja
    'MLP': '#2ca02c',            # Verde
    'NODE': '#9467bd',           # Roxo
    'TabNet': '#8c564b',         # Marrom
    'TabTransform': '#d62728'    # Vermelho
}

fig = go.Figure()

for architecture in architectures:
    y_values = []
    text_values = []
    color_values = []

    for strategy in strategies:
        strategy_data = data[strategy]
        value = next((item[1] for item in strategy_data if item[0] == architecture), 0)
        y_values.append(value)
        text_values.append("<b>{:.2%}</b>".format(value))
        color_values.append(colors[architecture])

    fig.add_trace(go.Bar(
        name=architecture,
        x=strategies,
        y=y_values,
        text=text_values,
        textposition="outside",
        textangle=0,
        textfont=dict(size=10),
        marker=dict(color=color_values)
    ))

fig.update_layout(
    font=dict(size=12),
    plot_bgcolor='rgba(0,0,0,0)',
    barmode='group',
    bargap=0.15,
    bargroupgap=0.1,
    legend=dict(
        x=0,
        y=1.0,
        bgcolor='rgba(255, 255, 255, 0)',
        bordercolor='rgba(255, 255, 255, 0)'
    ),
    xaxis=dict(title='Strategy'),
    yaxis=dict(
        title='Score',
        tickformat=".0%"
    ),
    title={
        'text': "Architecture Performance by Strategy",
        'y':0.9,
        'x':0.5,
        'xanchor': 'center',
        'yanchor': 'top'
    }
)

fig.show()
© www.soinside.com 2019 - 2024. All rights reserved.