亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Matplotlib 注釋文本在軸外擴展

Matplotlib 注釋文本在軸外擴展

滄海一幻覺 2021-11-02 13:53:32
我有一個帶有多個點的散點圖,有時會重疊,所以每個點上都有一個懸停框注釋(使用這里的解決方案來創建這個)。為了處理多個點和有時很長的描述,注釋中有一個換行符。問題在于多行,注釋框會向上構建而不是向下使其超出軸,如下所示。有沒有辦法讓文本從軸正下方的行開始,然后構建到繪圖中?相關代碼:import matplotlib.pyplot as pltimport 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.RdYlGnfig,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在它下面
查看完整描述

1 回答

?
臨摹微笑

TA貢獻1982條經驗 獲得超2個贊

我認為代碼問這個簡單的問題如何對齊文本或注釋有點矯枉過正。


這是通過verticalalignmentorva參數(或horizontalalignment/ ha)完成的。將其設置為"top"從頂部對齊文本。


使用xytext和textcoords參數(就像在鏈接的代碼中一樣)以點為單位為文本提供一些偏移量(即獨立于圖形的大?。?/p>


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

http://img1.sycdn.imooc.com//6180d2900001bfbf03830249.jpg

查看完整回答
反對 回復 2021-11-02
  • 1 回答
  • 0 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號