我有一个包含多个点的散点图,有时会重叠,因此每个点上都有一个悬停框注释(使用solution here来创建它)。为了处理多个点和有时很长的描述,注释中存在换行符。问题在于多行,注释框向上而不是向下,使其超出轴,如下所示。有没有办法让文本从轴正下方的行开始,然后构建到图中?
相关代码:
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
位于 8: I
位置,然后是 8: I
在其下方
最佳答案
我认为代码询问如何对齐文本或注释的简单问题有点矫枉过正。
这是通过verticalalignment
或va
参数(或horizontalalignment
/ha
)完成的。将其设置为“top”
以从顶部对齐文本。
使用xytext
和textcoords
参数(就像在链接的代码中一样)给文本一些以点为单位的偏移量(即独立于图形的大小) )。
import matplotlib.pyplot as plt
fig,ax = plt.subplots()
annot = ax.annotate("Three\nLine\nText", xy=(0, 1), xycoords='axes fraction',
xytext=(5,-5), textcoords="offset points",
bbox=dict(boxstyle="round", fc="w"), va="top")
plt.show()
关于python - Matplotlib 注释文本在轴外扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54582213/