python - Matplotlib 注释文本在轴外扩展

标签 python python-3.x matplotlib

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

相关文章:

python - 从 python 执行 scp 时出错

python - Python 中的多态性和构造函数行为

python - 同时填充 Pandas 数据框中相关列中的缺失值

python - 更改列表的 boolean 列表的某个索引也会更改其他索引

python - 向 Dataframe 添加新列并设置 MultiIndex

python - Flask + SqlAlchemy 修改表

Python:Xpath 为 For 循环中的每个 DIV 获取值时出现问题

matplotlib - 为 pyplot 对象设置 alpha channel ?

python - 如何以彩色显示 tiff 文件?

python - 在 python 中用 4 个数组数据绘制 3D 曲面图