【问题标题】:Show the final y-axis value of each line with matplotlib用 matplotlib 显示每条线的最终 y 轴值
【发布时间】:2011-06-11 23:33:30
【问题描述】:

我正在使用 matplotlib 绘制带有一些线条的图形,并且我想在每条线在右侧结束的位置旁边显示最终的 y 值,如下所示:

任何解决方案或指向 API 相关部分的指针?我很困惑。

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

【问题讨论】:

  • 感谢图片嵌入编辑!

标签: python matplotlib


【解决方案1】:

虽然 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()

这会将文本 8 points 放置在轴右侧的右侧,即每个图的最大 y 值处。您还可以添加箭头等。请参阅http://matplotlib.sourceforge.net/users/annotations_guide.html(如果您希望文本垂直居中于给定的 y 值,您也可以更改垂直对齐方式。只需指定va='center'。)

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

【讨论】:

    【解决方案2】:

    选项 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
    

    【讨论】:

    • 第一个选项可以完成这项工作(大多数情况下,请参阅我上面的评论),但我真的很喜欢第二个!必须手动设置相同的轴格式化程序,但这没问题。谢谢!
    • 但是y轴为对数刻度时会有些困难。绘制的数字好像不是新轴。如果第二个 y 轴也设置为对数刻度,则不会绘制数字。
    【解决方案3】:

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

    【讨论】:

    • 如何在数据框中按组赋值?
    猜你喜欢
    • 1970-01-01
    • 2021-03-22
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2017-09-19
    • 1970-01-01
    相关资源
    最近更新 更多