Home > Blockchain >  plot non-continuous function?
plot non-continuous function?

Time:09-06

Consider this simple program to plot a function:

import matplotlib.pyplot as plt
import numpy as np

def f(t):
    return t if t < 3 else 10-t
 
x = np.arange(0.0, 5.0, 0.1)

plt.plot(x, f(x), 'b-')
plt.show()

This gives an error in f because t is a numpy array. This works when I just return t in f(t): then I get a plot. Is it somehow possible to give plt.plot a function which is called for each x value explicitly? I also tried to use np.fromfunction before to generate the y values like so y = np.fromfunction(f, (50,)) but then f is also called with an array directly instead of the single values. Although the doc says: "Construct an array by executing a function over each coordinate." (https://numpy.org/doc/stable/reference/generated/numpy.fromfunction.html#numpy.fromfunction)

CodePudding user response:

Try

import matplotlib.pyplot as plt
import numpy as np

def f(t):
    return t if t < 3 else 10-t
F = np.vectorize(f)
x = np.arange(0.0, 5.0, 0.1)

plt.plot(x, F(x), 'b-')
plt.show()
  • Related