gpt4 book ai didi

python - 扩展到轴外的 Matplotlib 注释文本

转载 作者:太空宇宙 更新时间:2023-11-04 00:04:38 28 4
gpt4 key购买 nike

我有一个包含多个点的散点图,有时会重叠,因此每个点上都有一个悬停框注释(使用 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()

注释中的一行文本看起来如何

enter image description here

注释中两行文本的外观(悬停点与两点重叠)。理想情况下,0: A8: I,然后是 8: I

enter image description here

最佳答案

我认为用代码来询问如何对齐文本或注释这个简单问题有点矫枉过正。

这是通过 verticalalignmentva 参数(或 horizo​​ntalalignment/ha)完成的。将其设置为 "top" 以从顶部对齐文本。

使用 xytexttextcoords 参数(就像在链接代码中一样)给文本一些以点为单位的偏移量(即独立于图形的大小) ).

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()

enter image description here

关于python - 扩展到轴外的 Matplotlib 注释文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54582213/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com