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

如何在Matplotlib中为每个坐标点添加两个独立标签?

问题解决方法

问题出在你嵌套了内层循环,遍历所有titles元素,导致每个坐标点都会重复打印全部6个名称,最终所有名称重叠在同一位置。

修正后的代码如下:

import matplotlib.pyplot as plt

x = [0.0, -0.15, 0.04, 0.05, 0.1, -0.1]
y = [-0.1, -0.2, 0.0, 0.15, -0.06, 0.3]
titles = ["title 1", "title 2", "title 3", "title 4", "title 5", "title 6"]

plt.plot(x, y, 'r*')
plt.axis([-0.35, 0.35, -0.35, 0.35])

# 同时迭代x、y和对应的title,每个点只添加一次名称
for i, j, name in zip(x, y, titles):
    plt.text(i, j+0.02, '({}, {})'.format(i, j))
    plt.text(i, j+0.04, name)

plt.axvline(x=0, c="black")
plt.axhline(y=0, c="black")
plt.show()

关键改动说明

  • 使用zip(x, y, titles)将三个列表打包,确保每个坐标点对应唯一的名称标签
  • 移除内层的for name in titles循环,避免在单个点上重复打印所有名称

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 08:09:17