Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

plot non-continuous function?

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading