Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

附录:ipywidgets交互式可视化

当使用Pandas与Jupyter Notebook结合进行交互式可视化时,可以使用ipywidgets库来创建交互控件。下面是一个简单的例子:

首先,我们需要安装ipywidgets库:

pip install ipywidgets

然后,导入所需的库和模块:

from ipywidgets import interact

交互式的折线图

下面是一个简单的示例,演示如何使用ipywidgets创建一个交互式的折线图:

import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact

# 生成一些示例数据
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# 创建交互式函数
@interact
def plot_graph(show_sin=True, show_cos=True):
    plt.figure(figsize=(8, 3))
    
    if show_sin:
        plt.plot(x, y1, label='sin(x)')
    if show_cos:
        plt.plot(x, y2, label='cos(x)')
    
    plt.xlabel('x')
    plt.ylabel('y')
    plt.title('Interactive Plot')
    plt.legend()
    plt.grid(True)
    plt.show()
Loading...

请运行以上代码,生成交互图片

交互式的散点图

下面是另一个例子,展示如何使用ipywidgets创建一个交互式的散点图,用户可以通过滑块调整散点的数量:

import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact, IntSlider

# 创建一个交互式函数
@interact(num_points=IntSlider(min=10, max=1000, step=10, value=100))
def plot_scatter(num_points):
    # 生成随机数据
    x = np.random.rand(num_points)
    y = np.random.rand(num_points)
    
    # 绘制散点图
    plt.figure(figsize=(8, 3))
    plt.scatter(x, y)
    plt.title(f'Scatter Plot with {num_points} points')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.grid(True)
    plt.show()
Loading...

请运行以上代码,生成交互图片