有没有办法指定工具提示中显示的文本?

时间:2019-04-20 07:40:29

标签: python matplotlib tooltip

enter image description here我希望能够指定工具提示中显示的内容,默认是显示x和y,但是有一种方法可以将其更改为我想要的任何内容:

import matplotlib.pyplot as plt
import numpy as np
from mpldatacursor import datacursor

x1, y1 = np.random.random((2, 5))
x2, y2 = np.random.random((2, 5))

fig, ax = plt.subplots()
ax.plot(x1, y1, 'ro')
ax.plot(x2, y2, 'bo')

datacursor()
plt.show()

2 个答案:

答案 0 :(得分:0)

datacursor函数接受一个formatter参数,该参数允许用户指定标签格式。可以先指定每个图的标签,然后在数据光标中对其进行格式化(渲染)。在下面的示例代码中,每当单击光标各自的坐标点时,工具提示就会显示文本x1,y1(or x2,y2) values

ax.plot(x1, y1, 'ro', label='x1, y1 values')
ax.plot(x2, y2, 'bo', label='x2, y2 values')

datacursor(formatter='{label}'.format)

enter image description here

答案 1 :(得分:0)

例如,如果您想将x和y重命名为foo和bar, 您可以使用

datacursor(formatter="foo: {x:06.4f}\nbar: {y:06.4f}".format)

enter image description here

相关问题