Search code examples
pythonmatplotlibtextplot-annotations

automatically position text box in plot


Is there a way of telling pyplot.text() a location like you can with pyplot.legend()?

Something like the legend argument would be excellent:

plt.legend(loc="upper left")

I am trying to label subplots with different axes using letters (e.g. "A","B"). I figure there's got to be a better way than manually estimating the position.


Solution

  • I'm not sure if this was available when I originally posted the question but using the loc parameter can now actually be used. Below is an example:

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

    enter image description here