使用matplotlib imshow在for循环中显示numpy数组(Display numpy array in a for loop using matplotlib imshow)

编程入门 行业动态 更新时间:2024-10-23 08:28:28
使用matplotlib imshow在for循环中显示numpy数组(Display numpy array in a for loop using matplotlib imshow)

我有一个numpy数组,其元素在for循环中更新:

a = np.array([[1,2,3],[4,5,6],[7,8,9]]) for t in range(0,10): imshow(a) for i in range(0,a.shape[0]): for j in range(0,a.shape[1]): a[i][j] += 1

我想在每次迭代中显示数组,但imshow()不起作用,它只是在循环终止时显示图像。

PS。 我正在使用Ipython笔记本

我在网上发现了不同的东西,但是他们都没有在我的电脑上工作(例如我试图使用matplotlib的动画模块)

奇怪的是,如果我尝试使用标准Python提示符执行此示例( http://matplotlib.org/examples/animation/dynamic_image2.html ),则一切正常,而在Ipython笔记本计算机上则无法正常工作。 任何人都能解释我为什么?

笔记:

也许我简化了我的代码;

我正在研究森林火灾模型,数组是一个填充0 =空站点,1 =树,2 =火的网格。

在每个时间步骤(迭代)中:

一棵树被丢弃在一个随机选择的网站上,如果该网站是免费的,则树被种植 一棵树以概率f点燃

我想使用颜色映射来显示数组以可视化我的模型的演变

I have a numpy array whose elements are updated in a for loop:

a = np.array([[1,2,3],[4,5,6],[7,8,9]]) for t in range(0,10): imshow(a) for i in range(0,a.shape[0]): for j in range(0,a.shape[1]): a[i][j] += 1

I want to display the array at each iteration, but imshow() doesn't work, it just displays the image once the loop terminates.

ps. I'm using an Ipython notebook

I found different things on the web but none of them work on my computer (for example I tried to use matplotlib's animation module)

The strange thing is that if I try to execute this example (http://matplotlib.org/examples/animation/dynamic_image2.html) using the standard python prompt everything works fine, while on the Ipython notebook it doesn't work. Can anyone explain me why?

notes:

Maybe I oversimplified my code;

I'm working on a forest-fire model, the array is a grid filled with 0 = empty site, 1 = tree, 2 = fire.

At each time step (iteration):

a tree is dropped on a randomly chosen site and if the site is free the tree is planted a tree ignites with a probability f

I want to display the array using a colormap to visualize the evolution of my model

最满意答案

imshow(a)会将数组a的值绘制为像素值,但不会显示绘图。 要在for循环的每次迭代后查看图像,您需要添加show() 。

这应该做你想做的事情:

a = np.array([[1,2,3],[4,5,6],[7,8,9]]) for t in range(0,10): imshow(a) show() for i in range(0,a.shape[0]): for j in range(0,a.shape[1]): a[i][j] += 1

imshow(a) will plot the values of the array a as pixel values, but it won't display the plot. To view the image after each iteration of the for loop, you need to add show().

This should do what you want:

a = np.array([[1,2,3],[4,5,6],[7,8,9]]) for t in range(0,10): imshow(a) show() for i in range(0,a.shape[0]): for j in range(0,a.shape[1]): a[i][j] += 1

更多推荐

本文发布于:2023-07-05 07:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1034437.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   numpy   imshow   matplotlib   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!