首页 > 解决方案 > 我如何在 Python 中使用 Pyplot 函数?

问题描述

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

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)

标签: pythonnumpymatplotlib

解决方案


这里发生了一些事情

  1. 你不需要写出你正在导入的包的全名。您可以只使用别名来调用这些包并稍后将它们与这些别名一起使用。例如,这个。

    import numpy as np
    
  2. 您的 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()

推荐阅读