Matplotlib注释/文本:如何分别设置facecolor和edgecolor的alpha透明度?

lju*_*ten 4 python plot text alpha matplotlib

我正在使用 matplotlibplt.text函数向直方图添加文本框。在bbox参数中我指定了boxstylefacecoloredgecoloralpha。然而,当我运行它并显示绘图时,盒子的表面及其边缘相对于 都变得透明alpha。这会稍微改变两种颜色,我想保持我的边缘稳定。有谁知道如何设置 alpha 以使边框保持不透明 ( alpha=1) 但面部颜色可以设置为任何值 ( 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()
Run Code Online (Sandbox Code Playgroud)

She*_*ore 5

您可以首先计算两种颜色的 RGBA 序列,然后更改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
Run Code Online (Sandbox Code Playgroud)