单选按钮网格#

在二维网格布局中使用单选按钮。

通过向 layout 参数传递一个 (rows, cols) 元组,可以将单选按钮排列成二维网格。当你拥有多个相关选项,且以网格形式而非垂直列表形式展示效果更好时,此功能非常有用。

在本例中,我们创建了一个拾色器,使用单选按钮的二维网格来选择绘图的线条颜色。

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.widgets import RadioButtons

# Generate sample data
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2 * np.pi * t)

fig, (ax, ax_buttons) = plt.subplots(
    1,
    2,
    figsize=(8, 4),
    width_ratios=[4, 1.4],
)

# Create initial plot
(line,) = ax.plot(t, s, lw=2, color="red")
ax.set(xlabel="Time (s)", ylabel="Amplitude", title="Sine Wave - Click a color!")

# Configure the radio buttons axes
ax_buttons.set_facecolor("0.95")
ax_buttons.spines[:].set_color("0.8")
ax_buttons.set_title("Line Color")
# Create a 2D grid of color options (3 rows x 2 columns)
colors = ["red", "yellow", "green", "purple", "brown", "gray"]
radio = RadioButtons(ax_buttons, colors, layout=(3, 2))


def update_color(label):
    """Update the line color based on selected button."""
    line.set_color(label)
    fig.canvas.draw()
radio.on_clicked(update_color)


plt.show()
Sine Wave - Click a color!, Line Color

参考

本示例展示了以下函数、方法、类和模块的使用

标签: 样式:颜色 样式:条件 图表类型:线条 难度:中级 目的:展示

由 Sphinx-Gallery 生成的画廊