【问题标题】:automatically position text box in matplotlib在 matplotlib 中自动定位文本框
【发布时间】:2019-11-30 01:33:54
【问题描述】:

有没有办法像使用 pyplot.legend() 一样告诉 pyplot.text() 一个位置?

像传奇这样的论点会很棒:

plt.legend(loc="upper left")

我正在尝试使用字母(例如“A”、“B”)标记具有不同轴的子图。我认为必须有比手动估计位置更好的方法。

谢谢

【问题讨论】:

    标签: python textbox matplotlib


    【解决方案1】:

    只需使用annotate 并指定轴坐标。例如,“左上角”将是:

    plt.annotate('Something', xy=(0.05, 0.95), xycoords='axes fraction')
    

    您还可以更花哨并指定一个恒定的偏移量:

    plt.annotate('Something', xy=(0, 1), xytext=(12, -12), va='top'
                 xycoords='axes fraction', textcoords='offset points')
    

    更多解释参见例子here和更详细的例子here

    【讨论】:

    • 如果使用这个作为图例,偏移量应该是(8, -8)。亲眼所见。
    【解决方案2】:

    我不确定这在我最初发布问题时是否可用,但现在可以实际使用 loc 参数。下面是一个例子:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.offsetbox import AnchoredText
    
    # make some data
    x = np.arange(10)
    y = x
    
    # set up figure and axes
    f, ax = plt.subplots(1,1)
    
    # loc works the same as it does with figures (though best doesn't work)
    # pad=5 will increase the size of padding between the border and text
    # borderpad=5 will increase the distance between the border and the axes
    # frameon=False will remove the box around the text
    
    anchored_text = AnchoredText("Test", loc=2)
    ax.plot(x,y)
    ax.add_artist(anchored_text)
    
    plt.show()
    

    【讨论】:

    • AnchoredText 似乎无法处理loc="best"
    【解决方案3】:

    这个问题已经很老了,但是根据Add loc=best kwarg to pyplot.text(),到目前为止(2019 年)还没有通用的解决方案,我使用legend() 和以下解决方法来获得简单文本框的自动放置:

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.patches as mpl_patches
    
    x = np.linspace(-1,1)
    fig, ax = plt.subplots()
    ax.plot(x, x*x)
    
    # create a list with two empty handles (or more if needed)
    handles = [mpl_patches.Rectangle((0, 0), 1, 1, fc="white", ec="white", 
                                     lw=0, alpha=0)] * 2
    
    # create the corresponding number of labels (= the text you want to display)
    labels = []
    labels.append("pi = {0:.4g}".format(np.pi))
    labels.append("root(2) = {0:.4g}".format(np.sqrt(2)))
    
    # create the legend, supressing the blank space of the empty line symbol and the
    # padding between symbol and label by setting handlelenght and handletextpad
    ax.legend(handles, labels, loc='best', fontsize='small', 
              fancybox=True, framealpha=0.7, 
              handlelength=0, handletextpad=0)
    plt.show()
    

    一般的想法是创建一个带有空行符号的图例,然后删除由此产生的空白。 How to adjust the size of matplotlib legend box? 帮助我处理了图例格式。

    【讨论】:

      猜你喜欢
      • 2017-12-06
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 2021-08-26
      • 2011-12-29
      • 2017-09-01
      • 1970-01-01
      相关资源
      最近更新 更多