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

4
我正在使用 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()
2个回答

5
你可以先计算出两种颜色的RGBA序列,然后仅针对“facecolor”的alpha参数进行更改,最后将修改后的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

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接