Search code examples
matplotlibalignmentpaddingtext-alignment

BoxStyle/FancyBboxPatch/bbox padding ignored by alignment in Matplotlib


I am trying to add a background to a text, and overlay it on a graph. The way I do it is to use the bbox parameter of pyplot.text.

My code:

import matplotlib.pyplot as plt
plt.xlim(0.4,0.6)
plt.ylim(-0.1,0.1)
bbox = dict(facecolor='pink', alpha=0.2, edgecolor='red', boxstyle='square,pad=0.5')
plot,= plt.plot([0.4,0.6],[0,0])
text = plt.text(0.5, 0, 'foo goo', color='gold', size=50, bbox=bbox, horizontalalignment='center', verticalalignment='bottom')
plt.show()

The output:

bbox BoxStyle FancyBboxPatch ignores padding in alignment

As you can see, verticalalignment='bottom' considers only the bottom of the text, ignoring the padding of the bbox. Is there any 'native' means to correct this? If not, how should I offset the coordinates correctly to compensate for the padding?


Solution

  • The box has a margin padding of 0.5 times the fontsize of 50 pts. This means you want to offset the text 25 points from a position in data coordinates.

    Fortunately, using an Annotation instead of Text allows to do exactly that. Creating an Annotation can be done via .annotate, which takes a xytext and a textcoords argument for exactly such purpose.

    import matplotlib.pyplot as plt
    plt.xlim(0.4,0.6)
    plt.ylim(-0.1,0.1)
    bbox = dict(facecolor='pink', alpha=0.2, edgecolor='red', boxstyle='square,pad=0.5')
    plot,= plt.plot([0.4,0.6],[0,0])
    
    text = plt.annotate('foo goo', xy=(0.5, 0), xytext=(0,0.5*50), textcoords="offset points", 
                        color='gold', size=50, bbox=bbox, ha='center', va='bottom')
    
    plt.show()
    

    enter image description here