在 python 中用 matplotlib 绘图并添加数据标签

我们在 python 中调用 matplotlib 库来绘制曲线图时,下面的方法可以给曲线中的点添加数据标签:

# -*- coding: utf-8 -*-
import time
import matplotlib.pyplot as plt

def showResult(xList, yList, title, xLabel, yLabel):
    plt.plot(xList, yList, 'g*-')
    plt.title(title)
    plt.xlabel(xLabel)
    plt.ylabel(yLabel)
    for x, y in zip(xList, yList):
        plt.text(x, y+0.3, str(y), ha='center', va='bottom', fontsize=10.5)
    plt.savefig('fig'+str(int(time.time()))+'.jpg')
    plt.show()

x_arr = [1, 2, 3, 4, 5, 6]
y_arr = [1, 4, 9, 16, 25, 36]
showResult(x_arr, y_arr, 'title', 'x', 'y')

其中:

for x, y in zip(xList, yList):
    plt.text(x, y+0.3, '%.0f'%y, ha='center', va='bottom', fontsize=10.5)

逐个获取需要标注的点的横纵坐标 x与 y,然后在位置 (x, y+0.3) 处以 10.5 的字体显示出 y 的值,’center’ 和 ‘bottom’ 分别指水平和垂直方向上的对齐方式。
绘制的图像如下:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/yueyinlizun/article/details/80329451
今日推荐