python - 使用 matplotlib 绘制列表中的函数

标签 python numpy matplotlib

我一直在尝试使用 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/

相关文章:

python - 如何处理 Tkinter 中的窗口关闭事件?

python - 你将如何在 Python 中压缩未知数量的列表?

python - 尝试将字符串数组转换为具有混合给定数据类型的数组时出现 ValueError

python - 如何在matplotlib中设置刻度之间的固定间距

python - 如果轴标签属于列表,则更改轴标签的颜色/字体粗细

python - scipy-cluster 生成的树状图不显示

python - 在 python 中使用图像处理计算粒子

python - 使用 boto3 删除 CloudFront 分配

python - Numpy/PyTorch - 如何用不同维度的索引分配值?

python - numpy 数组 - unravel_index of argmax v. argmax of sum