簡體   English   中英

如何在 matplotlib 中制作多列文本注釋?

[英]How to make a multi-column text annotation in matplotlib?

matplotlib 的legend()方法有一個ncol參數,用於在多列中布置內容。

我想在文本注釋中做同樣的事情。

我可以將多行文本字符串(即包含\\n s 的字符串)傳遞給annotate() ,但是如何將內容排列成兩列?

  • 使用制表符? 他們似乎什么都不做
  • 使用兩個單獨的文本注釋? 但我想要兩列周圍的圓形邊框(bbox)
  • 使用像ncol這樣的東西? 它可以根據我要求的列數包裝列

我找不到一個很好的方法來做到這一點,所以我寫了一個函數來完成工作。 嘗試一下,看看它是否滿足您的需求。

def place_column_text(ax, text, xy, wrap_n, shift, bbox=False, **kwargs):
    """ Creates a text annotation with the text in columns.
    The text columns are provided by a list of strings.
    A surrounding box can be added via bbox=True parameter.
    If so, FancyBboxPatch kwargs can be specified.
    
    The width of the column can be specified by wrap_n,
    the shift parameter determines how far apart the columns are.
    The axes are specified by the ax parameter.

    Requires:
    import textwrap
    import matplotlib.patches as mpatches
    """
    # place the individual text boxes, with a bbox to extract details from later
    x,y = xy
    n = 0
    text_boxes = []
    for i in text:
        text = textwrap.fill(i, wrap_n)
        box = ax.text(x = x + n, y = y, s=text, va='top', ha='left',
                         bbox=dict(alpha=0, boxstyle='square,pad=0'))
        text_boxes.append(box)
        n += shift
    
    if bbox == True: # draw surrounding box
        # extract box data
        plt.draw() # so we can extract real bbox data
        # first let's calulate the height of the largest bbox
        heights=[]
        for box in text_boxes:
            heights.append(box.get_bbox_patch().get_extents().transformed(ax.transData.inverted()).bounds[3])
        max_height=max(heights)
        # then calculate the furthest x value of the last bbox
        end_x = text_boxes[-1].get_window_extent().transformed(ax.transData.inverted()).xmax
        # draw final
        width = end_x - x
        fancypatch_y = y - max_height
        rect = mpatches.FancyBboxPatch(xy=(x,fancypatch_y), width=width, height=max_height, **kwargs)
        ax.add_patch(rect)

這是它的使用:

import matplotlib.patches as mpatches
import textwrap

fig, ax = plt.subplots(2,2,sharex=True, sharey=True,figsize=(16,12))
fig.subplots_adjust(hspace=0.05, wspace=0.05)
ax1, ax2, ax3, ax4 = ax.flatten()

for a in ax.flatten():
    a.plot(range(0,20),range(0,20), alpha=0)

# the text to be split into columns and annotated
col_text = ['Colum 1 text is this sentence here.',
            'The text for column two is going to be longer',
            'Column 3 is the third column.',
            'And last but not least we have column 4. In fact this text is the longest.']

# use the function to place the text
place_column_text(ax=ax1,text=col_text, xy=(1,10), wrap_n=10, shift=4.2)
place_column_text(ax=ax2,text=col_text, xy=(0,19), wrap_n=17, bbox=True, shift=5, ec='red', fc='w', boxstyle='square')
place_column_text(ax=ax3,text=col_text, xy=(2,18), wrap_n=6, bbox=True, shift=2.7, ec='blue', fc = 'blue' , alpha=0.3, boxstyle='round,pad=1')
place_column_text(ax=ax4,text=col_text, xy=(3,12), wrap_n=10, bbox=True, shift=3, ec='red', fc='w', boxstyle='circle, pad=3')

plt.show()

結果:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM