# Matplotlib plot format, x**2 as x^2 browsing

• posted
0

So when I plot, I noticed matplot doesn't like x^2 and other similar formats. Instead it wants Python based math expressions such as x**2.

How do I plot using x^2 notation instead of x**2? Another example is it only wants exp(x) instead of e^(x).

``````x = arange(-self.x_window, self.x_window, self.res)
try:
y = eval(self.tf.text.lower())
plt.plot(x, y, linewidth=3)
except:
return
``````

• posted
0

In my code, should I just detect for ^ or e and replace it with ** or exp, respectively?

By the way, the end goal here is to allow a user to enter "familiar" math notation into a text field and allow it to be processed. x**4 for example is not familiar notation.

• posted
0

I guess you'd have to use regular expressions to preprocess the user input before you plot. You have to be careful how you do it though, because e^ should become exp and not e**.

A quick and dirty solution would be to print a line to tell the user to use ** instead of ^ etc.

• posted
0

``````formula = formula.replace('e^(', 'exp(').replace('^', '**')
``````

• posted
0

Too smooth.

• posted
0

What if a user puts in 5x ( as in 5 times x) or any NUMBER next to x? Matplot only wants 5*x. How can I use string.replace to squeeze that * between them?

• I would bid for permitting both notations - in your final code. After all users are quite likely to come across both in their lives. (I certainly have.) :-)

• posted
0

`regex` is probably better here but...

``````def x_times(formula):
if 'x ' in formula:
for i in xrange(10):
formula = formula.replace('{}x '.format(i),
'{} * '.format(i))
return formula
``````

• posted
0

@Martin

Yes, agreed. Thank you.

The exp( ) example above inherently allows for both. Also, what ever the solution is for the 5x example should allow for both 5x and 5*x as well.

• posted
0

Also, think about e^x or e^-x or e^4 (without the brackets). For that you definitely need regular expressions.

``````import re

formula = re.sub(r'e\^(-?[x0-9.]+?)', 'exp(\1)', formula)
``````

Something like that, haven't tested it, but should give you a start if you want to do something with re.

Internal error.

Oops! Looks like something went wrong!