gpt4 book ai didi

python - Python中的Matplotlib-绘制形状并对其进行动画处理

转载 作者:行者123 更新时间:2023-12-04 18:16:46 24 4
gpt4 key购买 nike

因此,我代表一个 token 环网络(在SimPy中进行仿真),对matplotlib来说是个新手,但有人告诉我,这对于以视觉方式呈现我的仿真非常有用。

所以我四处搜寻,发现了如何绘制形状和线条-分别对轴使用add_patch和add_line(我相信)。所以现在我有了这个输出,这绝对不错:

(尚无法发布图片!)
http://img137.imageshack.us/img137/7822/screenshot20100121at120.png

但是我使用pylab.show()函数得到了这个,我想我想要的是使用pylab.plot()函数来实现这个,这样我就可以在我使用pylab.draw()进行仿真时更新它。之后。

我的代码如下:

plab.ion()

plab.axes()

for circ in self.circleList:
plab.gca().add_patch(circ)

for line in self.lineList:
plab.gca().add_line(line)

plab.axis('scaled')
plab.show()

其中circleList和lineList是包含图表上的圆和直线的列表

我可能在这里误解了一些简单的东西,但是实际上我找不到任何使用plot()函数不是基于图形的示例。

澄清:

我如何使用pylab.plot()而不是pylab.show()获得相同的输出?

最佳答案

使用plot方法复制图像:

from pylab import *

points = []
points.append((-0.25, -1.0))
points.append((0.7, -0.7))
points.append((1,0))
points.append((0.7,1))
points.append((-0.25,1.2))
points.append((-1,0.5))
points.append((-1,-0.5))
points.append((-0.25, -1.0))

a_line = plot(*zip(*points))[0]
a_line.set_color('g')
a_line.set_marker('o')
a_line.set_markerfacecolor('b')
a_line.set_markersize(30)
axis([-1.5,1.5,-1.5,1.5])

show()

根据评论编辑

这使用python多处理库在单独的进程中运行matplotlib动画。主进程使用队列将数据传递给它,然后更新绘图图像。
# general imports
import random, time
from multiprocessing import Process, Queue

# for matplotlib
import random
import numpy as np
import matplotlib
matplotlib.use('GTKAgg') # do this before importing pylab

import matplotlib.pyplot as plt
from matplotlib.patches import Circle


def matplotLibAnimate(q,points):

# set up initial plot
fig = plt.figure()
ax = fig.add_subplot(111)


circles = []
for point in points:
ax.add_patch(Circle(point,0.1))

a_line, = ax.plot(*zip(*points))
a_line.set_color('g')
a_line.set_lw(2)

currentNode = None
def animate(currentNode = currentNode):
while 1:
newNode = q.get()
if currentNode: currentNode.remove()
circle = Circle(newNode,0.1)
currentNode = ax.add_patch(circle)
circle.set_fc('r')
fig.canvas.draw()

# start the animation
import gobject
gobject.idle_add(animate)
plt.show()

#initial points
points = ((-0.25, -1.0),(0.7, -0.7),(1,0),(0.7,1),(-0.25,1.2),(-1,0.5),(-1,-0.5),(-0.25, -1.0))
q = Queue()
p = Process(target = matplotLibAnimate, args=(q,points,))
p.start()

# feed animation data
while 1:
time.sleep(random.randrange(4))
q.put(random.sample(points,1)[0])

当然,这样做之后,我认为您可以使用whatnick的图像解决方案更好地为您服务。我将创建自己的GUI,而不使用小部件中内置的matplotlibs。然后,我将通过生成PNG并交换它们来“动画化”我的GUI。

关于python - Python中的Matplotlib-绘制形状并对其进行动画处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2109265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com