如何';我在Python中使用Pyplot函数吗?

如何';我在Python中使用Pyplot函数吗?,python,numpy,matplotlib,Python,Numpy,Matplotlib,程序完成后,我无法显示结果。我希望看到一个速度与位置的图表,但由于某种原因,它没有显示出来。我的代码有问题吗 import numpy from matplotlib import pyplot import time,sys #specifying parameters nx=41 # number of space steps nt=25 #number of time steps dt=0.025 #width between time intervals dx=2/(nx-1

程序完成后,我无法显示结果。我希望看到一个速度与位置的图表,但由于某种原因,它没有显示出来。我的代码有问题吗

import numpy 
from matplotlib import pyplot 
import time,sys


#specifying parameters

nx=41 # number of space steps
nt=25  #number of time steps
dt=0.025 #width between time intervals
dx=2/(nx-1) #width between space intervals 
c=1 # the speed of the initial wave



#boundary conditions
u = numpy.ones(nx) 
u[int(0.5/dx):int(1/(dx+1))] = 2

un = numpy.ones(nx)

#initializing the velocity function
for i in range(nt):
un= u.copy()
for i in range(1,nx):
    u[i]= un[i] -c*(dt/dx)*(u[i]-u[i-1])


pyplot.xlabel('Position')
pyplot.ylabel('Velocity')
pyplot.plot(numpy.linspace(0,2,nx),u)

这里发生了一些事情

  • 您不需要写出要导入的包的全名。您可以使用别名来调用这些包,然后将它们与这些别名一起使用。例如,这一点

    import numpy as np
    
  • 你的dx值初始化将给你0,因为你是2除以40,这将给你一个零。您可以通过将表达式中的一个值设为浮点来初始化dx的值,如下所示

    dx=float(2)/(nx-1) #width between space intervals 
    
  • 正如Meowcolm Law在注释中建议的注释一样,将pyplot.show()添加到 显示图表。这是您的代码的编辑版本所喜欢的

    import numpy as np
    import matplotlib.pyplot as plt 
    import time,sys
    
    
    #specifying parameters
    
    nx=41 # number of space steps
    nt=25  #number of time steps
    dt=0.025 #width between time intervals
    dx=float(2)/(nx-1) #width between space intervals 
    c=1 # the speed of the initial wave
    
    
    
    #boundary conditions
    u = np.ones(nx) 
    u[int(0.5/dx):int(1/(dx+1))] = 2
    un = np.ones(nx)
    
    #initializing the velocity function
    for i in range(nt):
        un= u.copy()
    for i in range(1,nx):
        u[i]= un[i] -c*(dt/dx)*(u[i]-u[i-1])
    
    
    plt.xlabel('Position')
    plt.ylabel('Velocity')
    plt.plot(np.linspace(0,2,nx),u)
    plt.show()
    
    你可以加上

    %matplotlib inline
    

    以查看笔记本内的绘图。按照相同的指南,我错过了这一步。

    尝试在末尾添加
    pyplot.show()
    ,您的un=u。副本没有正确缩进。