NameError: x is not defined - python

I'm trying to make a simple plotting function plot2d,
def plot2d(xmin,xmax,func):
x=np.linspace(xmin, xmax, num=50)
plt.plot(x,func)
plt.show()
The idea is you input the variable 'func' in terms of x, like x**2.
edit*
Here's the error:
>>> plot2d(-10,10, x**2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
edit**
I think the issue was that when you first call the function the linspace x hasn't be created yet. This worked:
import numpy as np
import matplotlib.pyplot as plt
def plot2d(xmin,xmax):
x=np.linspace(xmin, xmax, num=50)
func=input('Define fucntion: ')
plt.plot(x,func)
plt.show()

You might want to learn about lambda. Change your code a bit would suffice:
import numpy as np
import matplotlib.pyplot as plt
def plot2d(xmin,xmax,func):
x=np.linspace(xmin, xmax, num=50)
plt.plot(x,func(x)) #func -> func(x)
plt.show()
#pass a unnamed lambda as a param:
plot2d(-10, 10, lambda x: x*x)

from pylab import *
def plot2d(xmin, xmax, func):
x=np.linspace(xmin,xmax,num=50)
y=func(x)
plot(x,y)
show()
def func(x):
y=x**2
return y
plot2d(0,10,func)
Result:

Related

Plotting Taylor series expansions from Sympy in MatPlotLib [duplicate]

iยดam trying to plot the function sin(x)/x and a taylor approximation of it.
i use python 3 and pyzo - the first plot works but i have problems converting the series coming from the sympy module to an numpy expression that would work.
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from sympy.abc import x
x = np.linspace(-10, 10, 100)
y = np.sin(x)/x #first function
plt.plot(x, y, 'k') #this is working fine
### this is a code that removes the "0(x**something)" part of
the series at the end
i found it here http://pastebin.com/ZNQakWP7
def series(expr, x, x0, n, removeO=False):
"""
sympy bugs avoided
"""
# expr_series = expr.series(x, x0, n)
# return expr_series.removeO() if removeO else expr_series
expansion = list()
for t in expr.lseries(x, x0):
p = t.as_coeff_exponent(x)[1]
if p < n:
expansion.append(t)
else:
break
if not removeO:
expansion.append(sp.O(x**n))
return sp.Add(*expansion)
### my code continued ####
y_t=series(sp.sin(x)/x,x,0,6,removeO=True)
if i look at y_t now i get this approximation
out: x**4/120 - x**2/6 + 1
Now i try to convert this to numpy in order to plot it as i did with the first function.
f_t = lambdify(x, y_t,modules=['numpy'])
x = np.linspace(-10, 10, 100) #i do this because x has
#been a symbolic variable before
plt.plot(x, y_t, 'b') #this is where the problem occurs
i get the first plot also a second error message:
File "<console>", line 1, in <module>
File "F:\pyzo2013_0_2_2\lib\site-packages\matplotlib\pyplot.py", line 2832, in plot
ret = ax.plot(*args, **kwargs)
File "F:\pyzo2013_0_2_2\lib\site-packages\matplotlib\axes.py", line 3998, in plot
for line in self._get_lines(*args, **kwargs):
How can i achieve my idea to plot something coming from sympy?
Another idea i had was to convert the sympy out from the series to a string and then parsing this somehow to a numpy expression. I would be thankful for any help here!
I think your problem is that this:
plt.plot(x, y_t, 'b') #this is where the problem occurs
should be something like:
plt.plot(x, f_t(x), 'b')
f_t is the lambdified series, so it is a callable function that evaluates its argument.
I used lambdify in the following example, and it works for me:
from sympy.abc import x
from sympy import sin, series
from sympy.utilities.lambdify import lambdify
import numpy as np
import matplotlib.pyplot as plt
func = sin(x)/x
taylor = series(func, n=6).removeO()
evalfunc = lambdify(x, func, modules=['numpy'])
evaltaylor = lambdify(x, taylor, modules=['numpy'])
t = np.linspace(-5.5, 5.5, 100)
plt.plot(t, evalfunc(t), 'b', label='sin(x)/x')
plt.plot(t, evaltaylor(t), 'r', label='Taylor')
plt.legend(loc='best')
plt.show()
Here's the plot generated by the script.

Fit with function that involves integral

I am trying to fit a graphic with a function that involves a integral.
If I don't use np.array(), there is a error: "Result from function call is not a proper array of floats."
And if I use np.array(), there is another error: x and y must have same first dimension, but have shapes (501,) and (1,).
How can I fix this?
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy.optimize import curve_fit
import sympy as sp
x1=[1,2,3,4,5]
y=[6,12,18,24,30]
x,a,t=sp.symbols('x a t')
def f(x,a):
return np.array([sp.integrate(t*x*a,(t,0,2))],dtype=float)
xFit=np.arange(0,5.01,0.01)
popt, pcov=curve_fit(f,x1,y)
plt.scatter(x1,y)
plt.plot(xFit,f(xFit,*popt),color="r")
print(popt[0])
The function f(x,a) expects scalar arguments, and returns a scalar value even if x is a vector. Try replacing your plot() line with this:
ystar = [f(_x, popt[0]) for _x in xFit]
plt.plot(xFit, ystar, color="r")
well... it seems to me that this resolved:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy.optimize import curve_fit
import sympy as sp
x1=[1,2,3,4,5]
y=[6,12,18,24,30]
x,a,t=sp.symbols('x, a, t', real=True)
g=sp.integrate(t*x*a,(t,0,2))
f=sp.lambdify((x,a),g)
xFit=np.arange(0,5.01,0.01)
popt, pcov=curve_fit(f,x1,y)
plt.scatter(x1,y)
ystar = [f(_x, popt[0]) for _x in xFit]
plt.plot(xFit, ystar, color="r")
print(popt[0])

Plotting a function with more than one variable in Matplotlib

import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
from ipywidgets.widgets import interact
sym.init_printing(use_latex="mathjax")
x, y, z, t = sym.symbols('x y z t')
We were given a function in class to write as code
\begin{equation}
p_w(z,t)=\frac{1}{\sqrt{\pi \left(1-\exp\left[-2 t\right]\right)}}
\exp\left[-\frac{\left(z-\exp\left[-t\right]\right)^{2}}{1-
\exp\left[-2t\right]}\right]
\end{equation}
which I have written as this
p_w = (1/(sym.sqrt((sym.pi)*(1-(sym.exp(-2*t))))))*(sym.exp((-(z-sym.exp(-t))**2)/(1-sym.exp(-2*t))))
Then find the partial differential equation
โˆ‚๐‘ก๐‘๐‘ค(๐‘ง,๐‘ก)=โˆ‚๐‘ง[๐‘ง๐‘๐‘ค(๐‘ง,๐‘ก)]+1/2 โˆ‚2๐‘ง๐‘๐‘ค(๐‘ง,๐‘ก)
which I have written as this:
LHS=sym.diff(p_w,t,1)
#differentiate once with respect to t
RHS=sym.diff(z*p_w,z,1)+((1/2)*(sym.diff(p_w,z,2)))
#now differentiate with respect to z
Now we need to plot it and can only use matplotlib/numpy/sympy libraries.
Plot ๐‘๐‘ค(๐‘ง,๐‘ก) for the three values t=0.1,1,10 in a ๐‘๐‘ค(๐‘ง,๐‘ก) versus z diagram.
Here's what I've got so far:
t_points=[0.1,1,10]
#pw = sym.lambdify(t,p_w)
mytspace=np.linspace(0,10,200)
#myzspace=pw(mytspace)
plt.xlabel("t axis")
plt.ylabel("z axis")
plt.plot(t_array,np.zeros(3),'bs')
I haven't studied multivariable calculus before so I'm a bit lost!
Since one of your variables is given (you know t must be t=0.1, t=1 or t=10) your only variable for plotting is z. I know you are using sympy for the calculations, but for plotting maybe it's simpler to just return p_w as a numpy array. You can define a function to return p_w as so:
import numpy as np
import matplotlib.pyplot as plt
def p_w(z, t):
p_w = (1/(np.sqrt((np.pi)*(1-(np.exp(-2*t))))))*(np.exp((-(z-np.exp(-t))**2)/(1-np.exp(-2*t))))
return p_w
This will give you a numpy array with the results of p_w(z, t) where z is an array and t is just one number. Then you can just iterate over the values of t that you need:
t_points=[0.1, 1, 10]
z = np.linspace(0,10,200)
for t in t_points:
plt.plot(z, p_w(z, t), label='t = {0}'.format(t))
plt.legend()
plt.show()
Result:

Plot/Convert an expression coming from sympy: Taylor series with matplotlib

iยดam trying to plot the function sin(x)/x and a taylor approximation of it.
i use python 3 and pyzo - the first plot works but i have problems converting the series coming from the sympy module to an numpy expression that would work.
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from sympy.abc import x
x = np.linspace(-10, 10, 100)
y = np.sin(x)/x #first function
plt.plot(x, y, 'k') #this is working fine
### this is a code that removes the "0(x**something)" part of
the series at the end
i found it here http://pastebin.com/ZNQakWP7
def series(expr, x, x0, n, removeO=False):
"""
sympy bugs avoided
"""
# expr_series = expr.series(x, x0, n)
# return expr_series.removeO() if removeO else expr_series
expansion = list()
for t in expr.lseries(x, x0):
p = t.as_coeff_exponent(x)[1]
if p < n:
expansion.append(t)
else:
break
if not removeO:
expansion.append(sp.O(x**n))
return sp.Add(*expansion)
### my code continued ####
y_t=series(sp.sin(x)/x,x,0,6,removeO=True)
if i look at y_t now i get this approximation
out: x**4/120 - x**2/6 + 1
Now i try to convert this to numpy in order to plot it as i did with the first function.
f_t = lambdify(x, y_t,modules=['numpy'])
x = np.linspace(-10, 10, 100) #i do this because x has
#been a symbolic variable before
plt.plot(x, y_t, 'b') #this is where the problem occurs
i get the first plot also a second error message:
File "<console>", line 1, in <module>
File "F:\pyzo2013_0_2_2\lib\site-packages\matplotlib\pyplot.py", line 2832, in plot
ret = ax.plot(*args, **kwargs)
File "F:\pyzo2013_0_2_2\lib\site-packages\matplotlib\axes.py", line 3998, in plot
for line in self._get_lines(*args, **kwargs):
How can i achieve my idea to plot something coming from sympy?
Another idea i had was to convert the sympy out from the series to a string and then parsing this somehow to a numpy expression. I would be thankful for any help here!
I think your problem is that this:
plt.plot(x, y_t, 'b') #this is where the problem occurs
should be something like:
plt.plot(x, f_t(x), 'b')
f_t is the lambdified series, so it is a callable function that evaluates its argument.
I used lambdify in the following example, and it works for me:
from sympy.abc import x
from sympy import sin, series
from sympy.utilities.lambdify import lambdify
import numpy as np
import matplotlib.pyplot as plt
func = sin(x)/x
taylor = series(func, n=6).removeO()
evalfunc = lambdify(x, func, modules=['numpy'])
evaltaylor = lambdify(x, taylor, modules=['numpy'])
t = np.linspace(-5.5, 5.5, 100)
plt.plot(t, evalfunc(t), 'b', label='sin(x)/x')
plt.plot(t, evaltaylor(t), 'r', label='Taylor')
plt.legend(loc='best')
plt.show()
Here's the plot generated by the script.

Gamma function plot in Python

So I'd like to plot simple gamma function, but I have some problems. My code is:
#!/usr/bin/env python
# -*- coding: cp1250 -*-
#import math
from scipy.special import *
#from scitools.std import *
from pylab import *
def f1(x):
return gamma(x)
x = linspace(-6, 6, 512)
y1 = f1(x)
# Matlab-style syntax:
plot(x, y1)
xlabel('x')
ylabel('y')
legend(r'$\Gamma(x)$')
grid(True)
show()
I tried importing the gamma function from math, and from scipy.special but I get the following error:
Traceback (most recent call last): File "D:/faxstuff/3.godina/kvantna/plotgamma.py", line 13, in y1 = f1(x) File "D:/faxstuff/3.godina/kvantna/plotgamma.py", line 9, in f1 return gamma(x) File "mtrand.pyx", line 1599, in mtrand.RandomState.gamma (numpy\random\mtrand\mtrand.c:8389) ValueError: shape <= 0
How to do it? This should be easy, but I seem to fail :(
One of the modules (pylab, I think) is shadowing the gamma function by the gamma random variable function. This works, but I had to turn off the call to legend (I'm not sure why, yet).
from scipy.special import gamma as Gamma
#from scitools.std import *
from pylab import *
def f1(x):
return Gamma(x)
x = linspace(-6, 6, 512)
y1 = f1(x)
gca().set_autoscale_on(False)
# Matlab-style syntax:
plot(x, y1)
xlabel('x')
ylabel('y')
# legend(r'$\Gamma(x)$')
axis([-6, 6, -100, 100])
grid(True)
show()
Try this in a Sage notebook:
# Simple example demonstrating how to interact with matplotlib directly.
# Comment plt.clf() to get the plots overlay in each update.
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
#interact
def plot_gamma(a=(1,(1,10)), loc=(0,(0,10)), scale=(1,(1,10))):
rv = stats.gamma(a, loc, scale)
x = np.linspace(-1,20,1000)
plt.plot(x,rv.pdf(x))
plt.grid(True)
plt.savefig('plt.png')
plt.clf()

Categories