Matplotlib调用annotate()标注点报缺少xy参数错误的解决方法
问题报错原因
- 核心触发原因是
plt.annotate()方法调用不符合参数要求:该方法至少需要2个必填位置参数,第一个为要显示的标注文本,第二个为xy参数指定标注绑定的坐标点,原代码仅传入1个参数,直接抛出参数缺失错误。 - 原代码还存在遍历逻辑错误:循环仅读取
I5[0]下的元素,既没有覆盖I5中存储的所有线段端点,还会因I5[0]仅存2个点、循环执行4次触发索引越界问题。
修正后可运行代码
import numpy as np import matplotlib.pyplot as plt I5 = [[(0.5, -0.5), (1.5, -0.5)], [(0.5, -0.5), (0.5, -1.5)], [(1.5, -0.5), (1.5, -1.5)], [(0.5, -1.5), (1.5, -1.5)]] fig = plt.figure() ax = fig.add_subplot(1, 1, 1) N=3 #len(inv_r)+1 X = np.arange(0,N,1) Y = -X # 提取I5中所有不重复的坐标点,避免重复标注 point_set = set() for seg in I5: for p in seg: point_set.add(p) # 逐个绘制点位+坐标标注 for x, y in point_set: # 绘制点位标记,设置更高层级保证显示在网格上方 ax.scatter(x, y, c='red', s=30, zorder=5) # 标注坐标文本,相对点位偏移5像素避免遮挡标记 ax.annotate(f'({x}, {y})', xy=(x, y), xytext=(5, 5), textcoords='offset points') x_sorted = np.sort(X) y_sorted = np.sort(Y) ax.set_xticks(x_sorted) ax.set_yticks(y_sorted) ax.set_xlim(x_sorted[0], x_sorted[-1]) ax.set_ylim(y_sorted[0], y_sorted[-1]) ax.grid() ax.set_aspect('equal', 'box') plt.show()
实现效果
运行代码后将生成等比例网格坐标系,4个目标点位会以红色圆点标记,每个点旁标注对应坐标值,和预期输出效果完全匹配。
内容的提问来源于stack exchange,提问作者Wiz123
相关产品推荐
相关产品推荐

