python - 调整文本背景透明度

标签 python text matplotlib plot transparency

我正在尝试在 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)).

enter image description here

关于python - 调整文本背景透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23696898/

相关文章:

javascript - JQuery:在 4 个字符后切断 div 文本

html - 事件页面不工作

python - K 表示绘图未正确显示

python - 如何使用 matplotlib 从数据框中加载条形图数据

matplotlib - 使用 Matplotlib 在 Jupyter Lab 3 中实时绘图

python - 将生成器与 tf.data 一起使用的最可扩展方式? tf.data 指南说 `from_generator` 的可扩展性有限

python - 什么决定了 python 的 help() 列出的方法?

带假期的python日历

Python字典到xlsx中的列

php - 使用禁用的文本框将信息上传到数据库