Forum Archive

plotting from a string

donnieh

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)
ccc

Try: s = eval(self.tf.text) however, be warned that Eval really is dangerous.

omz

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 in x_values.

donnieh

Thank you. I like dangerous.