【问题标题】:Matplotlib annotate/text: How can I set alpha transparency for facecolor and edgecolor separately?Matplotlib 注释/文本:如何分别为 facecolor 和 edgecolor 设置 alpha 透明度?
【发布时间】:2020-09-30 10:28:48
【问题描述】:

我正在使用 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()

【问题讨论】:

    标签: python matplotlib plot text alpha


    【解决方案1】:

    您可以先计算两种颜色的 RGBA 序列,然后更改 facecolor 的 alpha 参数only,然后将修改后的 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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-23
        • 2011-07-02
        • 1970-01-01
        • 1970-01-01
        • 2013-04-18
        相关资源
        最近更新 更多