我试图使用DataCursor方法(https://stackoverflow.com/a/4674445/1301710)使用matplotlib标记点。我有几千点,并希望看到他们的鼠标悬停标签。但是,有两点不同:一个是散点图,另一个是两个,我想为每个点标注名称,而不仅仅是x,y坐标。使用matplotlib在鼠标悬停的散点图上标记除x,y坐标以外的标签上的点
这里是我的代码
import os
import matplotlib.pyplot as plt
class DataCursor(object):
text_template = 'x: %0.2f\ny: %0.2f'
x, y = 0.0, 0.0
xoffset, yoffset = -20, 20
text_template = 'x: %0.2f\ny: %0.2f'
def __init__(self, ax, labels,x,y):
self.ax = ax
self.xlist = x
self.ylist = y
self.labels = labels
self.annotation = ax.annotate(self.text_template,
xy=(self.x, self.y), xytext=(self.xoffset, self.yoffset),
textcoords='offset points', ha='right', va='bottom',
bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')
)
self.annotation.set_visible(False)
def __call__(self, event):
self.event = event
xdata, ydata = event.artist.get_data()
#self.x, self.y = xdata[event.ind], ydata[event.ind]
self.x, self.y = event.mouseevent.xdata, event.mouseevent.ydata
self.label = self.labels[self.xlist.index(self.x)]
if self.x is not None:
self.annotation.xy = self.x, self.y
self.annotation.set_text(self.label)
self.annotation.set_visible(True)
event.canvas.draw()
def process():
#code to make ht_dict here
# ht_dict has the following format: 'ht1' = [nov14count, nov21count] where each key is a string and each value is a list of two integers
print("Start making scatter plot..")
hts = []
nov14 = []
nov21 = []
for key in ht_dict.keys():
nov14.append(ht_dict[key][0])
nov21.append(ht_dict[key][1])
hts.append(key)
fig = plt.figure()
scatter = plt.scatter(nov14, nov21)
fig.canvas.mpl_connect('pick_event', DataCursor(plt.gca(), hts, nov14, nov21))
scatter.set_picker(5)
plt.show()
process()
我虽然收到以下错误:
AttributeError: 'CircleCollection' object has no attribute 'get_data'
我希望能够看到在X存储在列表HTS鼠标悬停字符串,并y坐标分别存储在nov14和nov21列表中相同的索引处。我不知道该怎么做这个错误,并会感谢任何帮助。 我的另一个问题是(从尝试对DataCursor线程中现有的阴谋的变化),使用索引返回标签,因为我目前正在做会给我一个值不存在列表错误,因为点击值可能与列表中的值不完全相同。你有没有更好的方法来显示某个点的标签/名称的建议?
任何指导或指向我可以阅读的文档的指针,将不胜感激。
谢谢!
你必须在你的代码中的一些问题缩进。 – xApple