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

本文介绍如何使用Python的matplotlib库为绘制的曲线图中的每个点添加数据标签,通过具体示例代码展示了设置文本标签的位置及样式的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们在 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’ 分别指水平和垂直方向上的对齐方式。
绘制的图像如下:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值