Matplotlib 交互式函数

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将学习如何使用Matplotlib中的交互式函数。这些交互式函数包括ginput、waitforbuttonpress和手动放置clabel。本实验的目的是帮助你了解如何使用这些函数在Matplotlib中创建交互式绘图。在本实验结束时,你将能够使用Matplotlib中的交互式函数创建和修改绘图。

虚拟机提示

虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问Jupyter Notebook进行练习。

有时,你可能需要等待几秒钟让Jupyter Notebook完成加载。由于Jupyter Notebook的限制,操作验证无法自动化。

如果你在学习过程中遇到问题,请随时向Labby提问。课程结束后提供反馈,我们将立即为你解决问题。

通过点击三个点定义一个三角形

在这一步中,我们将通过点击三个点来定义一个三角形。我们将使用ginputwaitforbuttonpress函数来实现这一点。ginput函数允许我们用鼠标在绘图上选择点,而waitforbuttonpress函数则等待按钮按下事件。

import time
import matplotlib.pyplot as plt
import numpy as np

def tellme(s):
    print(s)
    plt.title(s, fontsize=16)
    plt.draw()

plt.figure()
plt.xlim(0, 1)
plt.ylim(0, 1)

tellme('你将定义一个三角形,点击开始')

plt.waitforbuttonpress()

while True:
    pts = []
    while len(pts) < 3:
        tellme('用鼠标选择3个角点')
        pts = np.asarray(plt.ginput(3, timeout=-1))
        if len(pts) < 3:
            tellme('点太少,重新开始')
            time.sleep(1)  ## 等待一秒

    ph = plt.fill(pts[:, 0], pts[:, 1], 'r', lw=2)

    tellme('满意吗?按键点击表示是,鼠标点击表示否')

    if plt.waitforbuttonpress():
        break

    ## 清除填充
    for p in ph:
        p.remove()

根据到三角形角点的距离绘制等高线

在这一步中,我们将根据到三角形角点的距离绘制等高线。我们将定义一个关于单个点距离的函数,并根据这个函数绘制等高线。

## 定义一个关于单个点距离的优美函数
def f(x, y, pts):
    z = np.zeros_like(x)
    for p in pts:
        z = z + 1/(np.sqrt((x - p[0])**2 + (y - p[1])**2))
    return 1/z

X, Y = np.meshgrid(np.linspace(-1, 1, 51), np.linspace(-1, 1, 51))
Z = f(X, Y, pts)

CS = plt.contour(X, Y, Z, 20)

tellme('使用鼠标选择等高线标签位置,中间按钮结束')
CL = plt.clabel(CS, manual=True)

缩放

在这一步中,我们将对绘图进行缩放。我们将使用ginput函数选择缩放框的两个角点,并使用waitforbuttonpress函数完成缩放。

tellme('现在进行嵌套缩放,点击开始')
plt.waitforbuttonpress()

while True:
    tellme('选择缩放的两个角点,中间鼠标按钮完成')
    pts = plt.ginput(2, timeout=-1)
    if len(pts) < 2:
        break
    (x0, y0), (x1, y1) = pts
    xmin, xmax = sorted([x0, x1])
    ymin, ymax = sorted([y0, y1])
    plt.xlim(xmin, xmax)
    plt.ylim(ymin, ymax)

tellme('全部完成!')
plt.show()

总结

在本实验中,我们学习了如何使用Matplotlib中的交互式函数来创建和修改绘图。我们使用ginputwaitforbuttonpress以及手动放置clabel来定义一个三角形、根据到三角形角点的距离绘制等高线以及对绘图进行缩放。通过使用这些函数,我们可以创建交互式绘图,让用户能够与数据进行交互并更详细地探索数据。