Matplotlib annotatetext。如何分别设置facecolor和edgegecolor的alpha透明度?

问题描述 投票:0回答:1

我在使用matplotlib plt.text 函数来为我的直方图添加一个文本框。在 bbox 参数,我指定了 boxstyle, facecolor, edgecoloralpha. 然而,当我运行这个程序并显示该图时,盒子的表面和它的边缘都变得透明,相对于 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()
python matplotlib plot text alpha
1个回答
0
投票

你可以先计算出两种颜色的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

0
投票

你可以用alpha值指定颜色https:/matplotlib.org3.1.0tutorialscolorscolors.html。对于带alpha的RGB,你可以使用这个,0和1之间的任何数字。(0.1, 0.2, 0.5, 0.3)

© www.soinside.com 2019 - 2024. All rights reserved.