Reputation: 42459
I need to draw a title for a plot using set_title(), where its background shows with some degree of transparency.
I've tried three methods (one taken from this answer) but none seems to work. They either make the font of the text or the edges transparent, but not the background itself.
MWE:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1)
ax.minorticks_on()
ax.grid(b=True, which='minor', color='k', linestyle='--', lw=0.5,
zorder=1)
# Method 1
ax.set_title("Title", x=0.5, y=0.92, fontsize=13, alpha=0.2,
bbox=dict(facecolor='none'))
# Method 2
# ax.set_title("Title", x=0.5, y=0.92, fontsize=13,
# bbox=dict(facecolor='none', alpha=0.2))
# Method 3
# t = ax.set_title("Title", x=0.5, y=0.92, fontsize=13)
# t.set_bbox(dict(facecolor='none', alpha=0.2, edgecolor='k'))
plt.savefig('test.png')
Output:
Upvotes: 2
Views: 3753
Reputation: 69223
You were almost there. The issue is that you have facecolor='none'
, so even with an alpha
set, there is nothing to make transparent, and you don't see the background at all.
You can change this by setting facecolor='white'
, for example, modifying your "Method 2":
ax.set_title("Title", x=0.5, y=0.92, fontsize=13,
bbox=dict(facecolor='white', alpha=0.5))
This has the side-effect of also making the black border transparent too.
A way to fix that issue is to explicitly define the facecolor
and edgecolor
as (R,G,B,A)
tuples, and make sure the edgecolor
has alpha=1
:
ax.set_title("Title", x=0.5, y=0.92, fontsize=13,
bbox=dict(facecolor=(1,1,1,0.5),edgecolor=(0,0,0,1)))
Upvotes: 6