Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
159 views
in Technique[技术] by (71.8m points)

python - Show the final y-axis value of each line with matplotlib

I'm drawing a graph with some lines using matplotlib and I want to display the final y value next to where each line ends on the right hand side like this: enter image description here

Any solutions or pointers to the relevant parts of the API? I'm quite stumped.

I'm using matplotlib 1.0.0 and the pyplot interface, e.g. pyplot.plot(xs, ys, f, xs_, ys_, f_).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While there's nothing wrong with Ofri's answer, annotate is intended especially for this purpose:

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

This places the text 8 points to the right of the right side of the axis, at the maximum y-value for each plot. 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'.)

Also, this doesn't rely on tick locations, so it will work perfectly for log plots, etc. Giving the location of the text in terms of the positions of the axis boundaries and its offset in points has a lot of advantages if you start rescaling the plot, etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...