簡體   English   中英

用 matplotlib 顯示每條線的最終 y 軸值

[英]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專門用於此目的:

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放置在軸右側的右側,即每個 plot 的最大 y 值處。 You can also add in arrows, etc. See http://matplotlib.sourceforge.net/users/annotations_guide.html (You can also change the vertical alignment, if you want the text vertically centered on the given y-value. Just specify va='center' 。)

此外,這不依賴於刻度位置,因此它非常適用於日志圖等。如果您開始,根據軸邊界的位置及其偏移量給出文本的位置有很多優勢重新調整 plot 等。

選項 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

非常有用的喬。 只有一個細節。 如果最終值不是最大值,則可以使用 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 標記了最終的 y 軸值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM