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

NLTK dispersion_plot纵轴显示反转问题求助(附环境版本与代码)

NLTK dispersion_plot 纵轴反转及显示异常解决办法

问题现象

使用NLTK的dispersion_plot功能时出现两个异常:

  • 纵轴(Y轴)显示顺序反转:预期aa在顶部、cccc在底部,实际顺序完全颠倒
  • 目标词显示错误:未在文本中出现的f本该无显示,结果bbb消失不见

环境版本

  • nltk 3.8.1
  • matplotlib 3.7.2
  • Python 3.9.13

测试代码

from nltk.draw.dispersion import dispersion_plot
words=['aa','aa','aa','bbb','cccc','aa','bbb','aa','aa','aa','cccc','cccc','cccc','cccc']
targets=['aa','bbb', 'f', 'cccc']
dispersion_plot(words, targets)

问题原因

matplotlib 3.7+版本调整了坐标轴的默认方向,而NLTK的dispersion_plot函数未适配此变化,导致Y轴顺序反转;同时原函数内部会过滤未出现的目标词,反转后标签与坐标轴位置不匹配,引发显示错误。

解决方法

方法1:自定义修复后的绘图函数

手动反转Y轴并修正标签映射,代码示例:

from nltk.draw.dispersion import dispersion_plot
import matplotlib.pyplot as plt

def fixed_dispersion_plot(words, targets):
    fig, ax = plt.subplots()
    # 调用原函数生成点图
    dispersion_plot(words, targets, ax=ax)
    # 反转Y轴恢复预期顺序
    ax.invert_yaxis()
    # 重新设置Y轴标签,保留所有目标词
    ax.set_yticks(range(len(targets)))
    ax.set_yticklabels(targets)
    plt.show()

# 测试调用
words=['aa','aa','aa','bbb','cccc','aa','bbb','aa','aa','aa','cccc','cccc','cccc','cccc']
targets=['aa','bbb', 'f', 'cccc']
fixed_dispersion_plot(words, targets)

方法2:降级matplotlib版本

将matplotlib降级到3.6.x版本,适配NLTK原函数逻辑:

pip install matplotlib==3.6.3 --force-reinstall

内容的提问来源于stack exchange,提问作者drpawelo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 04:07:17