[Python]初学者笔记:interact互动功能

这篇博客介绍了如何在Python中使用ipywidgets库创建交互式功能。通过示例展示了interact和interact_manual函数的应用,包括设置不同类型的参数(如数值、字符串、列表和字典),以及如何控制交互范围。示例涵盖了从简单的函数到绘制图形的交互操作。
摘要由CSDN通过智能技术生成

进行数据分析之前常要引用的函式库

%matplotlib inline

import numpy as np

import matplotlib.pyplot as plt

开发互动功能要引用的函式库

from ipywidgets import interact

example1:

定义好基本的function之后

def f(x):

print(x**2)

执行interact就有互动功能了

interact(f, x=2)

interact的初始value带入2.的话,就会让互动介面的最小单位变成浮点数

interact(f, x=2.)

也可以限定interact的範围

interact(f, x=(1.,10.))

example2

不同的参数,将会产生不同的interact互动介面

这个例子的参数是字串

def ShowX(x):

print(“您输入了{}”.format(x))

初始值带入”hi”

interact(ShowX,x=”hi”)

example3

def f(x):

print(x)

会产生下拉式选单(参数带入list),并印出taipei, taichung, tainan

interact(f, x=[“taipei”,”taichung”,”tainan”])

会产生下拉式选单(参数带入dictionary),并印出1, 2, 3

interact(f, x={“taipei”:1,”taichung”:2,”tainan”:3})

example4

x = np.linspace(0, 2*np.pi, 1000)

def draw(n):

y = np.sin(n*x)

设定线的粗细 = 5

plt.plot(x, y, lw=5)

在jupyter notebook裡面可不加,但是在其他的开发

介面,就要加,不然图形会出现异常

plt.show()

interact(draw,n=(1., 50.))

example5

进行数据分析之前常要引用的函式库

%matplotlib inline

import numpy as np

import matplotlib.pyplot as plt

开发互动功能要引用的函式库

这裡改成import interact_manual

每次都要手动按下执行按钮,才会产生interact画面

from ipywidgets import interact_manual

定义一个简单的function做範例

def f(x):

print(x * 2)

互动的结果将会在按下执行按钮之后才会显现

interact_manual(f, x=(1., 100.))

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值