Adjust text background transparency

I am trying to put some text with a background on the matplotlib shape, with the text and background becoming transparent. 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 translucent relative to the text background, but the background is not at all transparent relative to the line that it hides in the picture.

 t.figure.set_alpha(.5) 

and

 t.figure.patch.set_alpha(.5) 

also don't do the trick.

+6
source share
1 answer

alpha passed to plt.text() will change the transparency of the text font. To change the background, you must change alpha with 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 

enter image description here

+12
source

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


All Articles