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

matplotlib散点图添加标注不显示问题如何解决?

matplotlib散点图标注不显示的解决方案

问题根因

  • 核心问题:未定义ax变量就直接调用ax.annotate()方法,标注逻辑实际没有执行
  • 次要问题:代码中的"是HTML转义字符,不符合Python语法要求,需要替换为普通引号

正确实现代码

import matplotlib.pyplot as plt

x = [ 6.343056,  -2.5713196 , 6.0487113 ,  10.894953  , 13.541282    , 3.64124    ,-1.7216474 , -4.916564 , -1.2961074 , 6.835421 ]
y = [11.965563,   -3.6742558,  12.373212,    9.714097 ,  -0.56607884 , 10.242817  ,0.7512899  , 2.1867976 ,  3.8110814 , 12.3270445]
t = [9, 6, 6, 4, 1, 9, 3, 9, 0, 9]

# 显式创建画布和Axes对象,避免隐式接口混乱
fig, ax = plt.subplots(figsize=(16, 8), dpi=80)
scatter = ax.scatter(x, y, c=t, cmap='viridis', alpha=0.3)
# 遍历添加标注
for i, tag in enumerate(t):
    ax.annotate(f"{tag}", (x[i], y[i]),
                textcoords="offset points", 
                xytext=(0,10),
                ha='center')
plt.colorbar(scatter)
plt.show()

如果不想修改整体画布创建逻辑,也可以在循环前添加ax = plt.gca()获取当前激活的Axes对象,同样可以解决标注不显示的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:36:03