Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib: How to buffer label text?

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

buffered text in GIS

What I tried

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

Result

matplotlib exercises to recreate buffered text

So my question is

(How) is it possible (with reasonable effort) to recreate buffered text in matplotlib?

like image 879
ojdo Avatar asked Aug 21 '14 12:08

ojdo


1 Answers

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")])

Example output showing white text outlined in red

like image 146
chthonicdaemon Avatar answered Sep 19 '22 16:09

chthonicdaemon