42

I'm trying to put some text with a background on a matplotlib figure, with the text and background both transparent. The following code

import numpy as np
import matplotlib.pyplot as plt
plt.figure()
ax = plt.subplot(111)
plt.plot(np.linspace(1,0,1000))
t = plt.text(0.03,.95,'text',transform=ax.transAxes,backgroundcolor='0.75',alpha=.5)
plt.show()

makes the text semi-transparent relative to the text's background, but the background isn't at all transparent relative to the line it obscures in the figure.

t.figure.set_alpha(.5)

and

t.figure.patch.set_alpha(.5)

also don't do the trick.

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
Jon Rein
  • 868
  • 2
  • 8
  • 13

1 Answers1

78

The alpha passed to plt.text() will change the transparency of the text font. To change the background you have to change the alpha using Text.set_bbox():

t = plt.text(0.5, 0.5, 'text', transform=ax.transAxes, fontsize=30)
t.set_bbox(dict(facecolor='red', alpha=0.5, edgecolor='red'))
#changed first dict arg from "color='red'" to "facecolor='red'" to work on python 3.6

To remove the border of the text box, as suggested in the comment of @halt9k, you can use .set_bbox(dict(facecolor='white', alpha=0.5, linewidth=0)).

enter image description here

Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234