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.
The percentage of opacity is calculated as Opacity% = Opacity * 100 To set the opacity only to the background and not the text inside it. It can be set by using the RGBA color values instead of the opacity property because using the opacity property can make the text inside it fully transparent element.
Approach: We can use the opacity property in CSS which is used to change the opacity of an element. The value of the property can be set in a range of 0 to 1, where “0” is fully transparent and “1” is opaque. Any decimal value can be used in between to set the opacity accordingly.
Changing the opacity of the background color only To achieve this, use a color value which has an alpha channel—such as rgba. As with opacity , a value of 1 for the alpha channel value makes the color fully opaque. Therefore background-color: rgba(0,0,0,. 5); will set the background color to 50% opacity.
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
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