当我在顺序循环中填充 jupyter 中的数组并使用 plt.plot 语句打印数组时,我可以单独打印数组,但只有一个图。
import numpy as np
import matplotlib.pyplot as plt
import time
muarr = np.linspace(0,10,10)
print('muarray')
print(muarr)
z = np.linspace(0.0,1.0,10) # create an array
print('array z')
print(z)
def fillit(mu):
x = 10 # initial x value
for i in range(0,10): # fill n2-n1 iterations
z[i] = i * x * mu
return z # returning the array
for i in range(0,10):
mu = muarr[i] #for a specific horizontal axis location
print()
print('iteration '+ str(i))
print('muarray '+str(i))
print('mu = '+str(mu))
y=fillit(mu) # an array of 10 elements from 0 to 100*mu
print('array y is an array of 10 elements from 0 to 100*mu')
print (y)
x=y*0.0 + mu # dummy x value is all mu
print('array x is just all mu so that each x,y pt can be plotted')
print (x)
plt.plot(x,y,'ko',markersize=1) # k=black, plot small points
如图所示,我可以毫不费力地从控制台实时绘制 这里 但这在Jupyter中也不起作用。 当我从终端将该代码作为 python 脚本运行时,数组会打印出来,但根本没有绘图。
我希望绘图在生成数据时实时更新。这在 jupyter 中可能吗?
编辑:添加了另一个解决方案。在评论中操作..
感谢您的回复。但是,将 plot.show(( 放在放置它的位置只会生成 10 个单独的图形,而不会生成在同一图形上出现的连续迭代数据
这是Jupyter笔记本的适当解决方案。
%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
import time
muarr = np.linspace(0,10,10)
print('muarray')
print(muarr)
z = np.linspace(0.0,1.0,10) # create an array
print('array z')
print(z)
def fillit(mu):
x = 10 # initial x value
for i in range(0,10): # fill n2-n1 iterations
z[i] = i * x * mu
return z # returning the array
fig = plt.figure()
ax = fig.add_subplot(111)
plt.ion()
fig.show()
fig.canvas.draw()
for i in range(0,10):
mu = muarr[i] #for a specific horizontal axis location
print()
print('iteration '+ str(i))
print('muarray '+str(i))
print('mu = '+str(mu))
y=fillit(mu) # an array of 10 elements from 0 to 100*mu
print('array y is an array of 10 elements from 0 to 100*mu')
print (y)
x=y*0.0 + mu # dummy x value is all mu
print('array x is just all mu so that each x,y pt can be plotted')
print (x)
ax.plot(x,y,'ko',markersize=1)
fig.canvas.draw()
time.sleep(1)
如果你需要每次迭代的图,你必须在 for 循环的末尾,在 plt.plot 之后添加 plt.show((:
for i in range(0,10):
mu = muarr[i] #for a specific horizontal axis location
print()
print('iteration '+ str(i))
print('muarray '+str(i))
print('mu = '+str(mu))
y=fillit(mu) # an array of 10 elements from 0 to 100*mu
print('array y is an array of 10 elements from 0 to 100*mu')
print (y)
x=y*0.0 + mu # dummy x value is all mu
print('array x is just all mu so that each x,y pt can be plotted')
print (x)
plt.plot(x,y,'ko',markersize=1) # k=black, plot small points
plt.show()
您链接的答案会在循环后添加 plt.show((,因此它只会显示最后创建的 plt.plot((。事实上,链接的问题就是您可能需要的,因为 jupyter 和终端工作略有不同。