问题描述
我写了一个简单的代码来绘制红色圆圈。
import matplotlib.pyplot as plt
import numpy as np
from mpldatacursor import datacursor
lines = plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
datacursor(lines)
plt.show()
上面的代码生成pyplot如下:
我的问题是,当我单击绘图的红色标记时,如何将标签 (x, y) 从出现的弹出窗口更改为自定义标签?
是否可以仅显示此弹出窗口几秒钟?
1楼
您需要使用来自定义显示的数据。 例如,要强制 x 和 y 值都为整数,我们可以执行以下操作:
datacursor(lines, formatter='x: {x:.0f}\ny: {y:.0f}'.format)
您可以使用任何自定义格式化程序以任何方式更改显示的文本,包括标签本身。
datacursor(lines, formatter='my_x: {x:.0f}\nmy_y: {y:.0f}'.format)
您甚至可以编写一个完整的函数来格式化标签,而不是使用str.format
如上所示。
def myformatter(**kwarg):
label = 'My custom label at point ({x:.0f}, {y:.0f})'.format(**kwarg)
return label
datacursor(lines, formatter=myformatter)