Plot plot function in Python

I would like to build 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: return 1

Using NumPy I am creating an array

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

    array([ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ,  1.2,  1.4,  1.6,  1.8,  2. ,
        2.2,  2.4,  2.6,  2.8,  3. ,  3.2,  3.4,  3.6,  3.8,  4. ,  4.2,
        4.4,  4.6,  4.8])

I tried things like ...

import matplotlib.pyplot as plt
plt.plot(x,f(x))

Or...

vecfunc = np.vectorize(f)
result = vecfunc(t)

Or...

def piecewise(x):
 if x == 2: return 0
 else: return 1

import matplotlib.pyplot as plt
x = np.arange(0., 5., 0.2)
plt.plot(x, map(piecewise, x))

ValueError: x and y must have same first dimension

But I do not use these functions correctly, and now I just randomly guess how to do this.

Some answers begin there ... But the dots connect in a line on the plot. How do we just plot the dots?

enter image description here

+4
source share
4 answers

Some answers begin there ... But the glasses are connected to the line on the plot. How do we just plot the dots?

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

enter image description here

+4
source

The problem is that the function fdoes not accept the array as input, but only one. You can:

plt.plot(x, map(f, x))

map f, x , f .

+3

You can use np.piecewise in an array:

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

append works, but requires a bit of extra processing. np works fine piecewise. can just do it for any function:

`

import math
import matplotlib as plt

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

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

`

0
source

Source: https://habr.com/ru/post/1599734/


All Articles