Show the final y-axis value of each line with matplotlib
我正在使用 matplotlib 绘制带有一些线的图形,我想在每条线在右侧结束的位置旁边显示最终的 y 值,如下所示:
有任何解决方案或指向 API 相关部分的指针吗?我很困惑。
我正在使用 matplotlib 1.0.0 和 pyplot 接口,例如pyplot.plot(xs, ys, f, xs_, ys_, f_).
- 感谢您的图像嵌入编辑!
虽然 Ofri 的回答没有任何问题,但 annotate 专门用于此目的:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import matplotlib.pyplot as plt
import numpy as np x = np.arange(61).astype(np.float) plt.plot(x, y1) for var in (y1, y2): plt.show() |
这会将文本 8 点放置在轴右侧的右侧,即每个图的最大 y 值处。您还可以添加箭头等。请参阅 http://matplotlib.sourceforge.net/users/annotations_guide.html (如果您希望文本垂直居中于给定的 y 值,您也可以更改垂直对齐方式。只需指定va=’center’.)
此外,这不依赖于刻度位置,因此它可以完美地用于日志图等。根据轴边界的位置及其偏移量给出文本的位置有很多如果您开始重新调整绘图等的优势。
选项 1 – pyplot.text
1
|
pyplot.text(x, y, string, fontdict=None, withdash=False, **kwargs)
|
选项 2 – 使用第二个轴:
1
2 3 |
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 |
- 第一个选项可以完成这项工作(主要是看我上面的评论),但我真的很喜欢第二个!必须手动设置相同的轴格式化程序,但这没问题。谢谢!
- 但是,当 y 轴是对数刻度时,它有一些困难。绘制的数字好像不是新轴。如果第二个 y 轴也设置为对数比例,则不会绘制数字。
非常有用的乔。只有一个细节。如果最终值不是最大值,则可以使用 y[-1]。我添加了一条水平线来澄清。
1
2 3 4 5 6 |
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 轴值。
- 如何在数据框中按组分配值?
来源:https://www.codenong.com/6319155/