Matplotlib annotate/text:如何分别设置 facecolor 和 edgecolor 的 alpha 透明度?

Matplotlib annotate/text: How can I set alpha transparency for facecolor and edgecolor separately?

我正在使用 matplotlib plt.text 函数将文本框添加到我的直方图中。在 bbox 参数中,我指定了 boxstylefacecoloredgecoloralpha。然而,当我 运行 这个并显示绘图时,盒子的表面和它的边缘相对于 alpha 变得透明。这会稍微改变两种颜色,我只想保持边缘牢固。有谁知道一种设置 alpha 的方法,使边框保持不透明 (alpha=1),但可以将 facecolor 设置为任何值 (alpha = [0,1])。

谢谢。

import matplotlib.pyplot as plt
import statistics

fig, ax = plt.subplots()
ax.hist(x=data, bins='auto', color='#0504aa', alpha=0.7, rwidth=0.85)
plt.grid(axis='y', alpha=0.75)

textstr = '\n'.join((
    r'$n=%.2f$' % (len(data), ),
    r'$\mu=%.2f$' % (round(statistics.mean(data), 4), ),
    r'$\mathrm{median}=%.2f$' % (round(statistics.median(data), 4), ),
    r'$\sigma=%.2f$' % (round(statistics.pstdev(data), 4), )))

ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14,
        verticalalignment='top', bbox=dict(boxstyle='square,pad=.6',facecolor='lightgrey', edgecolor='black', alpha=0.7))

plt.show()

您可以指定带有 alpha 值的颜色 https://matplotlib.org/3.1.0/tutorials/colors/colors.html 对于带 alpha 的 RGB,您可以使用它,0 到 1 之间的任何数字 (0.1, 0.2, 0.5, 0.3)

您可以先计算两种颜色的 RGBA 序列,然后更改 only 的 alpha 参数 facecolor,然后将修改后的 RGBA 元组传递给text 函数

from matplotlib import colors

# Rest of your code

fc = colors.to_rgba('lightgrey')
ec = colors.to_rgba('black')

fc = fc[:-1] + (0.7,) # <--- Change the alpha value of facecolor to be 0.7

ax.text(0.05, 0.95, textstr, transform=ax.transAxes, fontsize=14,
        verticalalignment='top', bbox=dict(boxstyle='square,pad=.6',
        facecolor=fc, edgecolor=ec)) # <--- Assign the face and edgecolors