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
446 views
in Technique[技术] by (71.8m points)

python - Print string over plotted line (mimic contour plot labels)

The contour plot demo shows how you can plot the curves with the level value plotted over them, see below.

enter image description here

Is there a way to do this same thing for a simple line plot like the one obtained with the code below?

import matplotlib.pyplot as plt 

x = [1.81,1.715,1.78,1.613,1.629,1.714,1.62,1.738,1.495,1.669,1.57,1.877,1.385]
y = [0.924,0.915,0.914,0.91,0.909,0.905,0.905,0.893,0.886,0.881,0.873,0.873,0.844]

# This is the string that should show somewhere over the plotted line.
line_string = 'name of line'

# plotting
plt.plot(x,y)
plt.show()
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You could simply add some text (MPL Gallery) like

import matplotlib.pyplot as plt 
import numpy as np
x = [1.81,1.715,1.78,1.613,1.629,1.714,1.62,1.738,1.495,1.669,1.57,1.877,1.385]
y = [0.924,0.915,0.914,0.91,0.909,0.905,0.905,0.893,0.886,0.881,0.873,0.873,0.844]

# This is the string that should show somewhere over the plotted line.
line_string = 'name of line'

# plotting
fig, ax = plt.subplots(1,1)
l, = ax.plot(x,y)
pos = [(x[-2]+x[-1])/2., (y[-2]+y[-1])/2.]
# transform data points to screen space
xscreen = ax.transData.transform(zip(x[-2::],y[-2::]))
rot = np.rad2deg(np.arctan2(*np.abs(np.gradient(xscreen)[0][0][::-1])))
ltex = plt.text(pos[0], pos[1], line_string, size=9, rotation=rot, color = l.get_color(),
     ha="center", va="center",bbox = dict(ec='1',fc='1'))

def updaterot(event):
    """Event to update the rotation of the labels"""
    xs = ax.transData.transform(zip(x[-2::],y[-2::]))
    rot = np.rad2deg(np.arctan2(*np.abs(np.gradient(xs)[0][0][::-1])))
    ltex.set_rotation(rot)

fig.canvas.mpl_connect('button_release_event', updaterot)
plt.show()

which gives
enter image description here

This way you have maximum control.
Note, the rotation is in degrees and in screen not data space.

Update:

As I recently needed automatic label rotations which update on zooming and panning, thus I updated my answer to account for these needs. Now the label rotation is updated on every mouse button release (the draw_event alone was not triggered when zooming). This approach uses matplotlib transformations to link the data and screen space as discussed in this tutorial.


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

...