使用matplotlib显示每条线的最终y轴值

7 投票
3 回答
19045 浏览
提问于 2025-04-16 19:23

我正在用matplotlib画图,想在每条线的右边显示最后的y值,像这样:

这里插入图片描述

有没有什么解决办法或者相关的API部分可以参考?我有点迷茫。

我使用的是matplotlib 1.0.0和pyplot接口,比如pyplot.plot(xs, ys, f, xs_, ys_, f_)

3 个回答

4

非常有用,Joe。还有一个小细节。如果最后的值不是最大值,你可以用 y[-1]。我加了一条水平线来说明这个问题。

gbm = np.log(np.cumsum(np.random.randn(10000))+10000)
plt.plot(gbm)
plt.annotate('%0.2f' % gbm[-1], xy=(1, gbm[-1]), xytext=(8, 0), 
             xycoords=('axes fraction', 'data'), textcoords='offset points')
plt.axhline(y=gbm[-1], color='y', linestyle='-.')
plt.show()

图中标出了最后的 y 轴值。

9

选项 1 - 使用 pyplot.text 方法

pyplot.text(x, y, string, fontdict=None, withdash=False, **kwargs)

选项 2 - 使用 第二个坐标轴:

second_axes = pyplot.twinx() # create the second axes, sharing x-axis
second_axis.set_yticks([0.2,0.4]) # list of your y values
pyplot.show() # update the figure
31

虽然Ofri的回答没有问题,但其实annotate这个功能特别适合这个用途:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(61).astype(np.float)
y1 = np.exp(0.1 * x)
y2 = np.exp(0.09 * x)

plt.plot(x, y1)
plt.plot(x, y2)

for var in (y1, y2):
    plt.annotate('%0.2f' % var.max(), xy=(1, var.max()), xytext=(8, 0), 
                 xycoords=('axes fraction', 'data'), textcoords='offset points')

plt.show()

enter image description here

这个功能会把文字放在坐标轴右边8个的位置,正好在每个图的最高y值那里。你还可以添加箭头等等。想了解更多,可以查看这个链接:http://matplotlib.sourceforge.net/users/annotations_guide.html (如果你想让文字在指定的y值上垂直居中,只需要设置va='center'就可以了。)

而且,这个方法不依赖于刻度的位置,所以在对数图等情况下也能完美使用。通过坐标轴边界的位置和偏移量来确定文字的位置,这样在你重新调整图表大小的时候会有很多好处。

撰写回答