用Matplotlib在绘图上写数值 [英] Writing numerical values on the plot with Matplotlib

查看:92
本文介绍了用Matplotlib在绘图上写数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Matplotlib可以在图形上打印每个点的值吗?

Is it possible, with Matplotlib, to print the values of each point on the graph?

例如,如果我有:

x = numpy.range(0,10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])
pyplot.plot(x,y)

如何在绘图上显示y值(例如,在(0,5)点附近打印5,在(1,3)点附近打印3,等等)?

How can I display y values on the plot (e.g. print a 5 near the (0,5) point, print a 3 near the (1,3) point, etc.)?

推荐答案

您可以使用 annotate 命令将文本注释放置在所需的任何x和y值处.要将它们准确地放置在数据点上,您可以这样做

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

如果您希望注释稍微偏移一点,可以将annotate行更改为类似的

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

这篇关于用Matplotlib在绘图上写数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆