我正在使用FuncAnimation软件包制作高斯波包的电影,使用有限差分实空间方法来解决薛定谔方程.相关代码如下.基本上,当我运行它时,一切运作良好 - 一个电影弹出显示我想要的东西.但是,更改"frames ="参数实际上不会改变帧数.您可以看到我在我的animate函数中打印当前迭代.此计数器上升到"frames ="中指定的数字,但随后返回0并继续运行.动画运行得比指定的更远.即使我指定"frames = 1",电影也会无限期地继续播放(我试着让它继续运行一个下午).我对于发生的事情感到非常难过,但我相对肯定这是愚蠢的事情.
# Set up the matplotlib figure and axes
fig = plt.figure()
ax = plt.axes(xlim = (0, hamiltonian.L), ylim = (0, 3))
line, = ax.plot([], [], lw = 2)
time_text = ax.text(.02, .95, '', transform=ax.transAxes)
ax.grid()
def init():
"""initialize the animation"""
line.set_data([], [])
time_text.set_text('')
return line, time_text
def animate(i):
"""actually perform the animation"""
print i
global hamiltonian, wavepacket
hamiltonian.propagate(wavepacket)
line.set_data(wavepacket.x, wavepacket.psi_sq)
time_text.set_text('time = %.3f' % wavepacket.time_elapsed)
return line, time_text
# Now call the animator …Run Code Online (Sandbox Code Playgroud) 我正在生成一组3D数据的2D热图.我希望能够有一个机制来交互式地浏览每个窗格.下面是一个简单的示例代码,我希望能够通过滑动条(或其他方法)以交互方式查看两个窗格(即z = [0,1]).matplotlib可以实现这一点,还是生成图像文件后我需要做后期处理?
import numpy as np
from matplotlib import pyplot as plt
data = np.random.randint(10, size=(5, 5, 2))
data_slice = np.zeros((5,5))
for i in range(0, 5):
for j in range(0, 5):
data_slice[i][j] = data[i][j][0]
plt.imshow(data_slice, cmap='hot', interpolation='nearest')
plt.show()
Run Code Online (Sandbox Code Playgroud)
编辑:我希望能够以交互方式执行此操作,并且似乎可能的重复尝试自动执行此操作.
我有一个带有图像的 matplotlib 按钮小部件。单击按钮后,我想将图像更改为其他内容。我试过这个:
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
FIGURE = plt.figure()
ICON_PLAY = mpimg.imread('./ui/images/play.png')
ICON_PAUSE = mpimg.imread('./ui/images/pause.png')
def play(event):
print "Starting"
start_button.image = ICON_PAUSE
start_button = Button(plt.axes([0.1, 0.1, 0.8, 0.8]), '', image=ICON_PLAY)
start_button.on_clicked(play)
plt.show()
Run Code Online (Sandbox Code Playgroud)
事件处理程序被调用,但图像未更改。有人知道如何在构建后更改 matplotlib 按钮小部件的图像吗?
在寻找一种使用matplotlib制作动画交互式绘图的方法时,我在堆栈溢出文档中遇到了这段代码:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Slider
TWOPI = 2*np.pi
fig, ax = plt.subplots()
t = np.arange(0.0, TWOPI, 0.001)
initial_amp = .5
s = initial_amp*np.sin(t)
l, = plt.plot(t, s, lw=2)
ax = plt.axis([0,TWOPI,-1,1])
axamp = plt.axes([0.25, .03, 0.50, 0.02])
# Slider
samp = Slider(axamp, 'Amp', 0, 1, valinit=initial_amp)
def update(val):
# amp is the current value of the slider
amp = samp.val
# update curve
l.set_ydata(amp*np.sin(t))
# redraw canvas while …Run Code Online (Sandbox Code Playgroud)