我有一个带有多个点的散点图,有时会重叠,所以每个点上都有一个悬停框注释(使用这里的解决方案来创建这个)。为了处理多个点和有时很长的描述,注释中有一个换行符。问题在于多行,注释框会向上构建而不是向下使其超出轴,如下所示。有没有办法让文本从轴正下方的行开始,然后构建到绘图中?
相关代码:
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
x = np.random.rand(15)
y = np.random.rand(15)
names = np.array(list("ABCDEFGHIJKLMNO"))
c = np.random.randint(1,5,size=15)
norm = plt.Normalize(1,4)
cmap = plt.cm.RdYlGn
fig,ax = plt.subplots()
sc = plt.scatter(x,y,c=c, s=100, cmap=cmap, norm=norm)
annot = ax.annotate("", xy=(0.05, 0.95), xycoords='axes fraction',
bbox=dict(boxstyle="round", fc="w"),
zorder=1000)
annot.set_visible(False)
def update_annot(ind):
pos = sc.get_offsets()[ind["ind"][0]]
annot.xy = pos
text = "{}".format("\n".join([f"{n}: {names[n]}" for n in ind["ind"]]))
annot.set_text(text)
annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]])))
annot.get_bbox_patch().set_alpha(0.4)
def hover(event):
vis = annot.get_visible()
if event.inaxes == ax:
cont, ind = sc.contains(event)
if cont:
update_annot(ind)
annot.set_visible(True)
fig.canvas.draw_idle()
else:
if vis:
annot.set_visible(False)
fig.canvas.draw_idle()
fig.canvas.mpl_connect("motion_notify_event", hover)
plt.show()
注释中的一行文本看起来如何
注释中的两行文本看起来如何(悬停点与两点重叠)。理想情况下有0: A
where 8: I
is,然后8: I
在它下面
临摹微笑
相关分类