Skip to content Skip to sidebar Skip to footer

Plot Piecewise Function In Python

I would like to plot the following piecewise function in Python using Matplotlib, from 0 to 5. f(x) = 1, x != 2; f(x) = 0, x = 2 In Python... def f(x): if(x == 2): return 0 else:

Solution 1:

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

deff(x):
 if(x == 2): return0else: return1

x = np.arange(0., 5., 0.2)

y = []
for i inrange(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()

enter image description here

Solution 2:

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.

Solution 3:

You can use np.piecewise on the array:

x = np.arange(0., 5., 0.2)
import matplotlib.pyplotas plt
plt.plot(x, np.piecewise(x, [x  == 2, x != 2], [0, 1]))

Solution 4:

the append works but requires a little extra processing. np's piecewise works fine. could just do this for any function:

`

import math
import matplotlib as plt

xs=[]
xs=[x/10for x inrange(-50,50)]   #counts in tenths from -5 to 5

plt.plot(xs,[f(x) for x in xs])

`

Solution 5:

if you are using python 2.x, map() returns a list. so you can write code as this:

import matplotlib.pyplot as plt
import numpy as np


deff(t):
    if t < 10:
        return0;
    else:
        return t * t - 100;


t = np.arange(0, 50, 1)

plt.plot(t, map(f, t), 'b-')

plt.show()

if you are using python 3.x, map() returns a iterator. so convert the map to a list.

plt.plot(t, list(map(f, t)), 'b-')

Post a Comment for "Plot Piecewise Function In Python"