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

问题描述 投票:1回答:2

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()
python matplotlib tooltip
2个回答
1
投票

datacursor函数接受formatter arg,允许指定标签格式。可以先指定每个绘图的标签,然后在datacursor中进行格式化(渲染)。在下面的示例代码中,只要在各自的坐标点上单击光标,工具提示就会显示文本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
投票

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

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.