Dash opens a new pop-up window with a graph but doesn't show a graph on the app

I’m trying to plot a histogram of bi-grams in a dash app. Every time I run the dash code it opens a new pop-up window with my histogram and the server of the dash app shows nothing.

The code works in jupyter also in my IDE, but it is not working in Dash. Could someone help me find out what I am doing wrong?

Here is a minimal reproducible code.

Thanks in advance.

from dash import Dash, dcc, html, Output, Input, State, callback
import plotly.express as px
import dash_bootstrap_components as dbc


import pandas as pd
import numpy as np

from nltk.corpus import stopwords
import nltk
import re
from nltk.util import ngrams
from collections import Counter
import matplotlib.pyplot as plt

dict = {'ID': {0: 0,
  1: 1,
  2: 2,
  3: 3,
  4: 4,
  5: 5,
  6: 6,
  7: 7,
  8: 8,
  9: 9,
  10: 10},
 'comment_text': {0: 'Más impuestos a los ricos! Viva la justicia social!',
  1: 'Sigo sin entender que bajada de impuestos, se creen que somos tontos o que !!',
  2: 'Hay algunos comentarios, que de por sí, demuestran la inteligencia de quién los hace....',
  3: 'Para mi fue excelente la experiencia',
  4: 'Excelente',
  5: 'Héctor. Yo respeto a la persona que sabe lo que dice es cierto. Pero no trates de engañar a los ciudadanos diciendo embustes.',
  6: 'Espontáneos que pagan hacienda creo yo !',
  7: 'Pena qué no me toque a mí está subida de impuestos',
  8: 'A la clase alta le da igual; ya idearán una forma legal de escaquearse. La clase baja ( menos de 21000) se beneficiará. Y como siempre, la clase media es la más puteada.',
  9: 'Ante ese infierno fiscal, es necesario tipificar como delito el derroche de gasto de estos sinvergüenzas. Es intolerable una subida de impuestos para luego regalar el dinero a chiringuitos vagos y maleantes.',
  10: 'cuando pones a una incompetente en hacienda...pasa esto'}
}

df = pd.DataFrame(dict)

def cleanReviews(documents):
    cleanedReviews = []
    for document in documents:
        s = re.sub(r'[^a-zA-Z0-9\s]', '', document)
        s = re.sub('\s+',' ', s)
        s = str(s).lower()
        tokens = [token for token in s.split(" ") if token != ""]
        tokens = [word for word in tokens if word not in stopwords.words('spanish')]
        # tokens = [word for word in tokens if word not in ['alexa', 'echo', 'dot']]
        review = ' '.join(tokens)
        cleanedReviews.append(review)
    return(cleanedReviews)


def documentNgrams(documents, size):
    ngrams_all = []
    for document in documents:
        tokens = document.split()
        if len(tokens) <= size:
            continue
        else:
            output = list(ngrams(tokens, size))
        for ngram in output:
            ngrams_all.append(" ".join(ngram))
    cnt_ngram = Counter()
    for word in ngrams_all:
        cnt_ngram[word] += 1
    df = pd.DataFrame.from_dict(cnt_ngram, orient='index').reset_index()
    df = df.rename(columns={'index':'words', 0:'count'})
    df = df.sort_values(by='count', ascending=False)
    df = df.head(15)
    df = df.sort_values(by='count')
    return(df)

def plotNgrams(documents):
    bigrams = documentNgrams(documents, 2)
    bigram_hist = px.histogram(bigrams, x = 'words', y='count', labels={'words':'Bigrams', 'count':'Frequency'}).update_layout(yaxis_title="Frequency")
    return bigram_hist.show()


def textTrends(documents):
    cleanedReviews = cleanReviews(documents)
    plotNgrams(cleanedReviews)

hist = textTrends(df['comment_text'])

app = Dash(__name__)

app.layout = dbc.Container([
    dbc.Row([
        dbc.Col([
            dcc.Graph(id = 'histo-chart_comments', figure=hist),
            ], width=12)
    ]),
])
if __name__=='__main__':
    app.run(port=8001)

Hello @setegonz,

A couple of things weren’t quite right. Very close though, only slight modifications.

Please find the adjust snippet. I removed the show() from bigram_hist and then return the plotNgrams from the function call of textTrends.

def plotNgrams(documents):
    bigrams = documentNgrams(documents, 2)
    bigram_hist = px.histogram(bigrams, x = 'words', y='count', labels={'words':'Bigrams', 'count':'Frequency'}).update_layout(yaxis_title="Frequency")
    return bigram_hist


def textTrends(documents):
    cleanedReviews = cleanReviews(documents)
    return plotNgrams(cleanedReviews)
1 Like

I was quite close. Thanks for the correction, it works perfect.