Adjust registration inside matplotlib annotation block

I use the annotate method for an Axes object to add arrows with text to the graph. For instance:

 ax.annotate('hello world, xy=(1, 1), xycoords='data', textcoords='data', fontsize=12, backgroundcolor='w', arrowprops=dict(arrowstyle="->", connectionstyle="arc3") 

This works well, but I want to reduce the padding inside the annotation field. Essentially, I want the box to squeeze more tightly around the text. Is there a way to do this with arrowprops or bbox_props kwargs?

I am looking for something like borderpad that is available in legends, similar to what was discussed in this answer .

+1
source share
1 answer

Yes, but you will need to switch to a slightly different way of specifying the field. The "base" block does not support it, so you need to annotate to create the FancyBboxPatch associated with the text object. (The same syntax for the "fancy" field will work with text placed with ax.text , which is what it is for.)


In addition, before going much further, the current version of matplotlib (1.4.3) has some rather thorny bugs. (e.g. https://github.com/matplotlib/matplotlib/issues/4139 and https://github.com/matplotlib/matplotlib/issues/4140 )

If you see things like this: enter image description here

Instead of this: enter image description here

You might consider lowering to matplotlib 1.4.2 until the problem is fixed.


Let's look at your example as a starting point. I changed the background color to red and put it in the center of the shape to make it easier to see. I am also going to get away with the arrow (avoiding the error above) and just use ax.text instead of annotate .

 import matplotlib.pyplot as plt fig, ax = plt.subplots() a = ax.text(0.5, 0.5, 'hello world', fontsize=12, backgroundcolor='red') plt.show() 

enter image description here

To be able to change the padding, you need to use bbox kwarg for text (or annotate ). This makes the text using FancyBboxPatch , which supports padding (along with a few other things).

 import matplotlib.pyplot as plt fig, ax = plt.subplots() a = ax.text(0.5, 0.5, 'hello world', fontsize=12, bbox=dict(boxstyle='square', fc='red', ec='none')) plt.show() 

enter image description here

The default indent is pad=0.3 . (If I remember correctly, the units are fractions of the height / width of the text.) If you want to increase it, use boxstyle='square,pad=<something_larger>' :

 import matplotlib.pyplot as plt fig, ax = plt.subplots() a = ax.text(0.5, 0.5, 'hello world', fontsize=12, bbox=dict(boxstyle='square,pad=1', fc='red', ec='none')) plt.show() 

enter image description here

Or you can reduce it by inserting 0 or a negative number to decrease it:

 import matplotlib.pyplot as plt fig, ax = plt.subplots() a = ax.text(0.5, 0.5, 'hello world', fontsize=12, bbox=dict(boxstyle='square,pad=-0.3', fc='red', ec='none')) plt.show() 

enter image description here

+6
source

Source: https://habr.com/ru/post/978914/


All Articles