在绘图线上打印字符串(模拟轮廓绘图标签) [英] Print string over plotted line (mimic contour plot labels)

查看:101
本文介绍了在绘图线上打印字符串(模拟轮廓绘图标签)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

轮廓图演示显示了如何使用绘制的水平值绘制曲线在它们上方,请参见下文.

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

是否有一种方法可以对像下面的代码那样的简单线图执行相同的操作?

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

推荐答案

您只需添加一些文本即可( MPL Gallery )喜欢

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

给出

这样,您可以最大程度地控制自己.
请注意,旋转单位是度,屏幕上不是数据空间.

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

由于我最近需要自动旋转标签,这会在缩放和平移时进行更新,因此我更新了答案以解决这些需求.现在,标签的旋转在每次释放鼠标按钮时都会更新(缩放时不会单独触发 draw_event ).这种方法使用matplotlib转换来链接数据和屏幕空间,如本教程中所述.

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.

这篇关于在绘图线上打印字符串(模拟轮廓绘图标签)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆