I'd like to have a colored buffer around annotation text within a matplotlib. This screenshot taken in QGIS shows how it looks like (in red):
My naive approaches involved plotting 'Some text' twice, with different font size and font weight. The result looks not convincing both times. The bbox
solution "works", but does not have the same aesthetics as the buffered text.
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
# font size
plt.annotate(
'Some text', xy=(.5, .75), color=(.7, .7, .7),
ha='center', va='center', fontsize='20')
plt.annotate(
'Some text', xy=(.5, .75), color=(.2, .3, .8),
ha='center', va='center', fontsize='16')
# font weight
plt.annotate(
'Some text', xy=(.5, .5), color=(.7, .7, .7),
ha='center', va='center', fontsize='16', weight='bold')
plt.annotate(
'Some text', xy=(.5, .5), color=(.2, .3, .8),
ha='center', va='center', fontsize='16')
# bbox
plt.annotate(
'Some text', xy=(.5, .25), color=(.2, .3, .8),
ha='center', va='center', fontsize='16',
bbox=dict(fc=(.7, .7, .7), lw=0, pad=5))
(How) is it possible (with reasonable effort) to recreate buffered text in matplotlib?
There's a detailed demo over here of using path effects to outline a variety of graphical objects. Here is a minimal example focusing on the text element.
import matplotlib.pyplot as plt
import matplotlib.patheffects as pe
fig, ax = plt.subplots()
txt = ax.text(0.5, 0.5, "test",
size=20,
color='white',
path_effects=[pe.withStroke(linewidth=4, foreground="red")])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With