Skip to main content
 首页 » 编程设计

python之在 Matplotlib 中自定义复选按钮

2025年02月15日10yyy_WW

我正在尝试自定义 CheckButtons:

rax = plt.axes( 
        [0.55, 0.8, 0.08, 0.08], 
        facecolor=secondary_color 
    ) 
 
    check = CheckButtons(rax, ('Mn vs. Pn', 'ØMn vs. ØPn'), (True, True)) 

但找不到设置按钮框、标记和字体颜色的不透明度(alpha 参数)的方法。

我们将不胜感激

请您参考如下方法:

如 documentation of matplotlib.widgets.CheckButtons 中所示、标签、按钮矩形和(标记的)线可以从类实例访问。
使用 check = CheckButtons(..)

  • check.rectangles 将按钮的背景列表返回为 matplotlib.patches.Rectangle
  • check.labels 将标签列表返回为 matplotlib.text.Text
  • check.lines 返回两个作为标记的 matplotlib.lines.Line2D 的元组列表。

它们都有 set_alpha 方法。

要设置背景,最简单的方法是提供一种已经设置了 alpha 值的颜色,例如 col = (0,0,1,0.2),其中最后一个值是蓝色。这可以使用 facecolor 参数设置为复选按钮轴。

这是一个完整的例子。

import matplotlib.pyplot as plt 
from matplotlib.widgets import CheckButtons 
 
fig= plt.figure(figsize=(4,1.5)) 
ax = plt.axes([0.4, 0.2, 0.4, 0.6] ) 
ax.plot([2,3,1]) 
col = (0,0.3,0.75,0.2) 
rax = plt.axes([0.1, 0.2, 0.2, 0.6], facecolor=col ) 
check = CheckButtons(rax, ('red', 'blue', 'green'), (1,0,1)) 
for r in check.rectangles: 
    r.set_facecolor("blue")  
    r.set_edgecolor("k") 
    r.set_alpha(0.2)  
 
[ll.set_color("white") for l in check.lines for ll in l] 
[ll.set_linewidth(3) for l in check.lines for ll in l] 
for i, c in enumerate(["r", "b", "g"]): 
    check.labels[i].set_color(c) 
    check.labels[i].set_alpha(0.7) 
 
plt.show()