You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dash应用打开新弹窗却不展示bi-grams直方图问题求助

问题排查与修复

核心原因

你的代码里应该直接调用了plt.show(),这个方法会触发系统默认的matplotlib绘图窗口弹出,但Dash的网页渲染依赖自身的组件体系,不会把独立窗口的内容同步到网页上。

修复方案

Dash需要将图形转换成兼容格式,通过dcc.Graph组件渲染在页面中。下面是两种可行的修改方式:

方法1:将matplotlib图转为Plotly Figure(推荐,支持交互)

import dash
from dash import html, dcc
import matplotlib.pyplot as plt
from nltk.util import ngrams
from collections import Counter
from plotly.tools import mpl_to_plotly

app = dash.Dash(__name__)

# 生成双词组统计数据
text = "this is a test text this is another test sample text"
tokens = text.split()
bigrams = list(ngrams(tokens, 2))
bigram_counts = Counter(bigrams)

# 创建matplotlib Figure对象(不调用plt.show())
fig, ax = plt.subplots(figsize=(8, 4))
ax.bar(range(len(bigram_counts)), bigram_counts.values())
ax.set_xticks(range(len(bigram_counts)))
ax.set_xticklabels([f"{b[0]} {b[1]}" for b in bigram_counts.keys()], rotation=45, ha="right")
ax.set_ylabel("Frequency")
ax.set_title("Bi-gram Frequency Histogram")

# 转换为Plotly格式的Figure
plotly_fig = mpl_to_plotly(fig)

# 构建Dash布局,用dcc.Graph渲染图形
app.layout = html.Div([
    html.H3("双词组频率直方图"),
    dcc.Graph(figure=plotly_fig)
])

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

方法2:将matplotlib图转为Base64图片(静态展示)

如果不需要交互功能,也可以把图转成图片嵌入网页:

import dash
from dash import html
import matplotlib.pyplot as plt
from nltk.util import ngrams
from collections import Counter
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import io
import base64

app = dash.Dash(__name__)

# 生成双词组统计数据
text = "this is a test text this is another test sample text"
tokens = text.split()
bigrams = list(ngrams(tokens, 2))
bigram_counts = Counter(bigrams)

# 创建matplotlib Figure对象
fig, ax = plt.subplots(figsize=(8, 4))
ax.bar(range(len(bigram_counts)), bigram_counts.values())
ax.set_xticks(range(len(bigram_counts)))
ax.set_xticklabels([f"{b[0]} {b[1]}" for b in bigram_counts.keys()], rotation=45, ha="right")
ax.set_ylabel("Frequency")
ax.set_title("Bi-gram Frequency Histogram")

# 将Figure转为Base64编码的图片
img_buffer = io.BytesIO()
FigureCanvas(fig).print_png(img_buffer)
img_base64 = base64.b64encode(img_buffer.getvalue()).decode()

# 构建Dash布局,用html.Img嵌入图片
app.layout = html.Div([
    html.H3("双词组频率直方图"),
    html.Img(src=f"data:image/png;base64,{img_base64}", style={"width": "100%"})
])

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

关键注意点

  1. 移除所有plt.show()调用,避免弹出独立窗口。
  2. 确保安装必要依赖:pip install dash plotly matplotlib nltk
  3. 首次使用nltk的ngrams时,需要下载punkt资源:nltk.download('punkt')

内容的提问来源于stack exchange,提问作者Steven González

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 18:15:36