brenogil brenogil - 8 months ago 25
Python Question

Plotting functions from a list using matplotlib

I have been trying to print several equations I have using numpy and matplotlib.

The functions are stored on a text file, one equation per line. These equations look like this:


My idea was to iterate to each line, generate the plot and save it somewhere.
My code:

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.savefig(str( line + ".png"))

I get the results I want by removing the loops part and replacing
y = line

y = np.exp(6.6506+(-171.637)/(x*32))

How can I plot all equations in my txt file? Plots are very simple and 2D.


Use eval, with the usual reservations regarding security:

y = eval(line)

you may have to remove the new line \n from the lines you read from file with line.strip('\n')

drawing attention to eval security risks:

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.