I need assistance with Plotly dash error

Hello guys,

Can someone please help me understand what I am missing in my code below. I get an error “TypeError: a number is required” during the callback. I suspect its the values or labels but I cannot figure it out.

@app.callback(Output('sentiment-pie', 'figure'),
              Input('pie-update','interval'))
def update_pie_chart(n):
    df = pd.read_sql("SELECT sentiment FROM messages" ,conn)
    df['pos'] = count(df[df['sentiment']>= 0.05])
    df['neg'] = count(df[df['sentiment']<= -0.05])
    print(type(df['pos'].values()))
    

    labels=['positive','negative']
    
    values = pd.DataFrame(df['pos'],df['neg'])
    
    colors = ['#007F25', '#800000']

    trace = go.Pie(labels=labels,values=values,
                   hoverinfo='label+percent', textinfo='value', 
                   textfont=dict(size=20, color=colors['text']),
                   marker=dict(colors=colors, 
                               line=dict(color=colors['background'])))

    return {"data":[trace],'layout' : go.Layout(
                                                  title='Positive vs Negative sentiment for',
                                                  font={'color':colors['text']},
                                                  plot_bgcolor = colors['background'],
                                                  paper_bgcolor = colors['background'],
                                                  showlegend=True)}

Do you have the full Traceback of the error?

What I noticed is that you try to access colors["text"] and colors["background"]. This results in TypeError: list indices must be integers or slices, not str. A few lines before, you define colors as a list - but lists can only be accessed by an integer (= access by index) or slices (= access by range/step).

Here’s your code running without a problem (the colors are a bit messed up, I replaced colors[“text”] with colors[0] and colors[“background”] with colors[1]):

import plotly.graph_objects as go
import pandas as pd
from dash import Dash, html, dcc, Input, Output


app = Dash(__name__)

app.layout = html.Div([
    html.Button("Show pie", id="showpie", n_clicks=0),
    dcc.Graph(figure={}, id="pie")
])


@app.callback(
    Output("pie", "figure"),
    Input("showpie", "n_clicks"),
    prevent_initial_call=True
)
def get_pie(n):
    df = pd.DataFrame(
        [-0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3],
        columns=["sentiment"]
    )
    df_pos = df[df["sentiment"] >= 0].count()
    df_neg = df[df["sentiment"] < 0].count()

    values = [df_pos.sentiment, df_neg.sentiment]
    labels = ["positive", "negative"]
    colors = ["#007F25", "#800000"]

    fig = go.Figure()
    fig.add_trace(
        go.Pie(
            labels=labels,
            values=values,
            hoverinfo="label+percent",
            textinfo="value",
            textfont=dict(
                size=20,
                color=colors[0]  # 1st color in colors
            ),
            marker=dict(
                colors=colors,
                line=dict(
                    color=colors[1]  # 2nd color in colors
                )
            )
        )
    )

    fig.update_layout(
        title="Positive vs Negative sentiment for",
        font={"color": colors[0]},
        plot_bgcolor=colors[1],
        paper_bgcolor=colors[1],
        showlegend=True
    )

    return fig


if __name__ == "__main__":
    app.run_server(debug=True)

1 Like

Hello Yanboe,

It worked!

Thank you so much for the assistance. :hugs: