猿问

Matplotlib 注释文本在轴外扩展

我有一个带有多个点的散点图,有时会重叠,所以每个点上都有一个悬停框注释(使用这里的解决方案来创建这个)。为了处理多个点和有时很长的描述,注释中有一个换行符。问题在于多行,注释框会向上构建而不是向下使其超出轴,如下所示。有没有办法让文本从轴正下方的行开始,然后构建到绘图中?


相关代码:


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: Awhere 8: Iis,然后8: I在它下面


http://img3.mukewang.com/6180d28200013b8505580424.jpg

沧海一幻觉
浏览 148回答 1
1回答

临摹微笑

我认为代码问这个简单的问题如何对齐文本或注释有点矫枉过正。这是通过verticalalignmentorva参数(或horizontalalignment/ ha)完成的。将其设置为"top"从顶部对齐文本。使用xytext和textcoords参数(就像在链接的代码中一样)以点为单位为文本提供一些偏移量(即独立于图形的大小)。import matplotlib.pyplot as pltfig,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()
随时随地看视频慕课网APP

相关分类

Python
我要回答