我试图使用多个if
语句来检查某个条件,然后使用Python
中的matplotlib
来绘制一些数据。首先,我在一个目录上做os.walk
,得到文件列表,然后加载它们,最后打印并保存图形。这是我的密码:
def velocity():
plt.xlabel('$\mathrm{Iterations\/or\/Time}$')
plt.title(r'$\mathrm{Residual\/history}$')
plt.grid(True)
plt.yscale('log')
if 'Ux_0' in lf:
print "Entered"
plt.plot(time_x, value_x, color = 'r', label = 'x-vel')
elif 'Uy_0' in lf:
print "Entered"
plt.plot(time_y, value_y, color = 'b', label = 'y-vel')
elif 'Uz_0' in lf:
print "Entered"
plt.plot(time_z, value_z, color = 'g', label = 'z-vel')
plt.legend()
plt.savefig(os.path.join(plotsDir, 'velocity'), bbox_inches='tight', dpi=100)
plt.close()
return (time_x, value_x, lf)
return (time_y, value_y, lf)
return (time_z, value_z, lf)
for path, dirs, files in os.walk(logsDir, topdown=False):
for lf in files:
if 'Ux_0' in lf:
logFile = os.path.join(path, lf)
data_x = np.loadtxt(logFile)
time_x, value_x = data_x[:,0], data_x[:,1]
(time_x, value_x, lf) = velocity()
if 'Uy_0' in lf:
logFile = os.path.join(path, lf)
data_y = np.loadtxt(logFile)
time_y, value_y = data_y[:,0], data_y[:,1]
(time_y, value_y, lf) = velocity()
if 'Uz_0' in lf:
logFile = os.path.join(path, lf)
data_z = np.loadtxt(logFile)
time_z, value_z = data_z[:,0], data_z[:,1]
(time_z, value_z, lf) = velocity()
logDir
只有三个文件开始,它们是Ux_0
、Uy_0
和Uz_0
。有趣的是,在os.walk
之后,当我print
lf
时,我得到的文件顺序是Ux_0
、Uz_0
和Uy_0
。现在,由函数velocity()
生成的图形只有来自Ux_0
和Uz_0
的数据,而不是Uy_0
。但是,在我的函数中,如果Uy_0
和Uz_0
的顺序颠倒,使得我在Ux_0
之后有Uz_0
,如下图所示,我得到了所需的所有三个图。你知道吗
if 'Ux_0' in lf:
print "Entered"
plt.plot(time_x, value_x, color = 'r', label = 'x-vel')
elif 'Uz_0' in lf:
print "Entered"
plt.plot(time_z, value_z, color = 'b', label = 'z-vel')
elif 'Uy_0' in lf:
print "Entered"
plt.plot(time_y, value_y, color = 'g', label = 'y-vel')
plt.legend()
plt.savefig(os.path.join(plotsDir, 'velocity'), bbox_inches='tight', dpi=100)
plt.close()
return (time_x, value_x, lf)
return (time_y, value_y, lf)
return (time_z, value_z, lf)
我不知道是什么原因造成的。你知道吗
虽然Padraic对于
return
语句毫无意义是绝对正确的,但问题的实际原因是plt.savefig
命令的缩进和放置。你知道吗如果您查看
plt.savefig
语句的位置,它只在到达最后一个elif
时执行,即在lf
中找到Uz_0
。当Uz_0
是列表中的第二项时,绘图仅在该点保存,因此最后一个数据集被绘图但不保存。你知道吗您可能应该有一个在最后运行的
save_velocity()
函数。你知道吗代码清理:
你只会返回相同的值,其余的值是不可到达的,因此如果你在你的if中设置值,基于你认为你从你的速度函数得到不同的值,你不会:
函数在碰到return语句时结束,所以只要到达第一个语句,它就结束了。你知道吗
可以返回多个元素:
然后使用切片来分配
res = velocity(); a,b,c = res[2],res[3] ,res[4]
等。。提取和分组任何你想要的。你知道吗相关问题 更多 >
编程相关推荐