调整文本背景透明度

Jon*_*ein 10 python plot transparency text matplotlib

我试图在matplotlib图上放一些带背景的文字,文字和背景都是透明的.以下代码

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()
Run Code Online (Sandbox Code Playgroud)

使文本相对于文本的背景是半透明的,但背景相对于它在图中模糊的线条完全不透明.

t.figure.set_alpha(.5)
Run Code Online (Sandbox Code Playgroud)

t.figure.patch.set_alpha(.5)
Run Code Online (Sandbox Code Playgroud)

也不做伎俩.

Sau*_*tro 19

alpha传递给plt.text()将改变文本字体的透明度.要更改背景,您必须更改alpha使用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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 你也可以做`props = dict(...)`和`ax.text(... bbox = props)` (6认同)
  • 另外要删除边缘, `.set_bbox(dict(facecolor='white', alpha=0.5, linewidth=0))` (5认同)