Df.loc dont work with plotly

Hi Guys,

I need your help, i did get data from mysql, define the columns, create the dropdown to select the filter but my filter dont work, i test the function update_output and note that the value is set correctly but when i run the code i cannot filter the columns using the dropdown

df = DataFrame(pcclass.all_prices_group_sku())
df.columns = ['dates', 'site_name', 'preco', 'sku']
df.dates = df.dates.dt.strftime("%Y-%m-%d %H:%M:%S")
# criando o gráfico
fig = px.bar(df, x=df.dates, y=df.preco, color=df.site_name, barmode='group')
#fig = px.bar(df, x=df.preco, y=df.dates, color=df.site_name, barmode="stack")
opcoes = list(df.site_name.unique())
opcoes.append("Todos os Sites")
app.layout = html.Div(children=[
    html.H1(children=f'Lista de precios de la competencia SKU '),
    html.H2(children='Gráfico con comparación de precios del sitio web'),
    dcc.Dropdown(opcoes, value='Todas os Sites', id='lista_lojas'),
    dcc.Graph(id='grafico_quantidade_vendas',figure=fig)
])
@app.callback(
    Output('grafico_quantidade_vendas', 'figure'),[Input('lista_lojas', 'value')])

def update_output(value):
    if value == "Todos os Sites":
        fig = px.bar(df, x=df.dates, y=df.preco, color=df.site_name, barmode='group')
    else:
        tabela_filtrada = df.loc[df.site_name == value,:]
        fig = px.bar(tabela_filtrada, x=df.dates, y=df.preco, color=df.site_name, barmode='group')
    return fig

Its a bit hard to diagnose without any data to permit a working example, but why not just use df[df.site_name==value]to filter the dataframe when value has a selection.

I’d also consider replacing the if value=="Todos… condition with if value in df.site_name.unique() to make the output a bit more robust against bad input.

1 Like

My database mysql return this result

                     dates  site_name    preco             sku
0      2022-09-28 00:00:00      Winpy        0        210-BBCC
1      2022-09-26 00:00:00  Red Cetus        0       CONF-WISP
2      2022-09-26 00:00:00  Red Cetus        0      CONF-HOTEL
3      2022-09-26 00:00:00  Red Cetus        0  MS-WinSvr-2016
4      2022-09-26 00:00:00  Red Cetus        0  Windows 10 Pro
...                    ...        ...      ...             ...
19949  2022-09-25 00:00:00  Spdigital  999,990    NA0000052033
19950  2022-09-25 00:00:00  Spdigital  999,990    NA0000052035
19951  2022-09-25 00:00:00  Spdigital  999,990    NA0000056848
19952  2022-09-25 00:00:00  Spdigital  999,990    NA0000059827
19953  2022-09-25 00:00:00  Spdigital  999,990    NA0000056487

I solve the problem put the string of loc inside px.bar

def update_output(value):
    if value == "Todos os Sites":
        fig = px.bar(df, x=df.dates, y=df.preco, color=df.site_name, barmode='group')
    else:
        tabela_filtrada = df.loc[df.site_name == value,:]
        fig = px.bar(tabela_filtrada, x=tabela_filtrada.dates, y=tabela_filtrada.preco, color=tabela_filtrada.site_name, barmode='group')
    return fig