我一直在尝试使用 numpy 和 matplotlib 打印几个方程。
这些函数存储在一个文本文件中,每行一个方程。这些方程如下所示:np.exp(6.6506+(-171.637)/(x*32))
我的想法是迭代每一行,生成绘图并将其保存在某个地方。 我的代码:
import numpy as np
import matplotlib.pyplot as plt
source = "path/to/list.txt"
with open(source) as f:
for line in f.readlines():
x = np.linspace(0,200)
y = line
plt.plot(x,y)
plt.savefig(str( line + ".png"))
plt.close()
通过删除循环部分并替换 y = line
,我得到了我想要的结果
通过y = np.exp(6.6506+(-171.637)/(x*32))
如何绘制 txt 文件中的所有方程?绘图非常简单并且是二维的。
最佳答案
使用eval
,并保留有关安全性的常见保留:
y = eval(line)
您可能需要从使用 line.strip('\n')
从文件读取的行中删除新行 \n
提请注意评估
安全风险:
eval parses a string (any string given to it) and attempts to execute it... This is why it is generally considered a security risk and must only be used when it is certain that no malicious or harmful instructions will ever be passed to it. The risks involved are not trivial and the consequences potentially disastrous.
more about the dangers of eval - 由@Brenogil建议
关于python - 使用 matplotlib 绘制列表中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36814212/