如何在Matplotlib绘制的图像中为每个数据点添加标签?
给Matplotlib散点图数据点添加标签的实现方案
要给每个数据点添加标签,核心是遍历每组的x、y数据,使用plt.text()函数在对应位置附近插入文本标签。以下是修改后的完整代码,同时补充了图例方便区分不同系列:
import matplotlib.pyplot as plt # Sample data gflops_a = [72.3, 74.5, 79.6, 82.5] model_a_ACC = [9.3, 9.7, 11.2, 14.2] labels_a = ["1", "2", "3", "4"] # 自定义标签,可替换为需要的内容 gflops_b = [73.95, 75.2, 79.9, 82.8] model_b_ACC = [7.8, 8.3, 9.1, 9.9] labels_b = ["1", "2", "3", "4"] gflops_c = [74.3, 76.9, 82.3, 84.5] Set_ACC = [7.1, 7.8, 8.8, 9.7] labels_c = ["1", "2", "3", "4"] # Creating the line graph plt.figure(figsize=(3.8, 2.8)) # 绘制散点并保存返回的线对象,用于图例 line_a, = plt.plot(model_a_ACC, gflops_a, marker='o', linestyle='', label='Model A') line_b, = plt.plot(model_b_ACC, gflops_b, marker='^', linestyle='', label='Model B') line_c, = plt.plot(Set_ACC, gflops_c, marker='s', linestyle='', label='Set C') # 给每个数据点添加标签 for x, y, label in zip(model_a_ACC, gflops_a, labels_a): plt.text(x + 0.1, y + 0.1, label, fontsize=8) # 偏移量可根据图表调整 for x, y, label in zip(model_b_ACC, gflops_b, labels_b): plt.text(x + 0.1, y + 0.1, label, fontsize=8) for x, y, label in zip(Set_ACC, gflops_c, labels_c): plt.text(x + 0.1, y + 0.1, label, fontsize=8) # Adding titles and labels plt.xlabel('G') plt.ylabel('A') plt.legend() # 启用图例 plt.grid(True) plt.tight_layout() # Show the plot plt.show()
关键说明
- 自定义标签:
labels_a/labels_b/labels_c可以替换为任意你需要的文本(比如参数值、模型版本号等) - 位置调整:
x + 0.1, y + 0.1是让标签相对于数据点轻微偏移,避免遮挡标记点,可根据图表的坐标范围调整偏移量 - 字体大小:通过
fontsize参数可以控制标签的大小,适配图表尺寸
内容的提问来源于stack exchange,提问作者MFalam
相关产品推荐
相关产品推荐

