Some answers are starting to get there... But the points are being connected into a line on the plot. How do we just plot the points?
import matplotlib.pyplot as plt
import numpy as np
def f(x):
if(x == 2): return 0
else: return 1
x = np.arange(0., 5., 0.2)
y = []
for i in range(len(x)):
y.append(f(x[i]))
print x
print y
plt.plot(x,y,c='red', ls='', ms=5, marker='.')
ax = plt.gca()
ax.set_ylim([-1, 2])
plt.show()

Videos
Hi guys,
I'm using numpy and plotly to graph piecewise functions. I previously used matlab. I need help to essentially translate matlab piecewise functions into something I can use in python. Here's what I had in matlab:
Constant1 = 5; Constant2 = 10; Formula1 = @(x,y) x*Constant1; Formula2 = @(x,y) x*Constant2; MainFormula = @(x,y) [Formula1(x,y)*(y<=5) + Formula2(x,y)*(y>5)];
So what this would essentially do is make 'MainFormula' equal to 'Formula1' for all values of y less than or equal to 5, and it would make 'MainFormula' equal to 'Formula2' for all values of y greater than 5.
I would really appreciate any help with this.
Thanks
Some answers are starting to get there... But the points are being connected into a line on the plot. How do we just plot the points?
import matplotlib.pyplot as plt
import numpy as np
def f(x):
if(x == 2): return 0
else: return 1
x = np.arange(0., 5., 0.2)
y = []
for i in range(len(x)):
y.append(f(x[i]))
print x
print y
plt.plot(x,y,c='red', ls='', ms=5, marker='.')
ax = plt.gca()
ax.set_ylim([-1, 2])
plt.show()

The problem is that the function f does not take an array as input but a single numer. You can:
plt.plot(x, map(f, x))
The map function takes a function f, an array x and returns another array where the function f is applied to each element of the array.
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
def fun (n, x):
if n <= x <= n + 1:
return float(x) - n
elif n + 1 <= x <= n + 2:
return 2.0 - x + n
return 0.0
vfun = np.vectorize(fun)
x = np.linspace(0, 10, 1000)
y = vfun(3, x)
plt.plot(x, y, '-')
plt.show()
If you just want to visualize your data, you may try exporting it in a text file to visualize it with gnuplot. For your simple example, you may try to plot it in gnuplot directly as in this example.
In Matlab/Octave, if you have your function as pairs of data x1/y1 and x2/y2, you can plot them using plot( x1 , y1 , x2 , y2 ).