plotting from a string
-
I have a string from a textfield that I want to input as the math function. How do I take this string and allow the plot function to recognize it as a math expression?
t = arange(0.0, 2.0, 0.01) s = self.tf.text #text coming in from textfield is: 'sin(2*pi*t)' plt.plot(t, s)
Just to verify, the program works by setting s = to the function:
t = arange(0.0, 2.0, 0.01) s = sin(2*pi*t) plt.plot(t, s)
-
Try:
s = eval(self.tf.text)
however, be warned thatEval really is dangerous
.
-
I'll keep the UI part out of this to make the code simpler, but here's a start:
from numpy import arange import matplotlib.pyplot as plt from math import * x_values = arange(0.0, 2.0, 0.01) s = 'sin(2*pi*t)' y_values = [eval(s, globals(), {'t': t}) for t in x_values] plt.plot(x_values, y_values) plt.show()
The basic idea is to create a list (
y_values
) by evaluating your string as a Python expression once for each element inx_values
.
-
Thank you. I like dangerous.