我正在尝试在 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()
使文本相对于文本的背景是半透明的,但背景相对于它在图中遮挡的线完全不是透明的。
t.figure.set_alpha(.5)
和
t.figure.patch.set_alpha(.5)
也不要这样做。
最佳答案
传递给plt.text()
的alpha
将改变文本字体的透明度。要更改背景,您必须使用 Text.set_bbox()
更改 alpha
:
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
要去除文本框的边框,如@halt9k 的评论中所建议,您可以使用.set_bbox(dict(facecolor='white', alpha=0.5, linewidth=0))
.
关于python - 调整文本背景透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23696898/