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

时间:2011-06-11 23:33:30

标签: python matplotlib

我正在使用matplotlib绘制一些带有一些线条的图形,我想在右边的每一行的末尾显示最后的y值,如下所示: enter image description here

API的相关部分的任何解决方案或指针?我很难过。

我正在使用matplotlib 1.0.0和pyplot接口,例如pyplot.plot(xs, ys, f, xs_, ys_, f_)

3 个答案:

答案 0 :(得分:14)

虽然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 points 放置在轴右侧的右侧,每个绘图的最大y值。您还可以添加箭头等。请参阅http://matplotlib.sourceforge.net/users/annotations_guide.html(如果您希望文本垂直居中于给定的y值,也可以更改垂直对齐。只需指定va='center'。)

此外,这不依赖于刻度位置,因此它可以完美地用于对数图等。根据轴边界的位置及其在点的偏移量给出文本的位置具有很多优点如果你开始重新调整情节等等。

答案 1 :(得分:4)

选项1 - pyplot.text

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

选项2 - 使用second axes

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

答案 2 :(得分:1)

非常有用乔。只有一个细节。如果最终值不是最大值,则可以使用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()

Plot with final y-axis value marked.

相关问题