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 minimum of two arrays

I have two arrays for x-values and two corresponding arrays for y-values which I wish to plot.

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(-2,2,100)
x2 = np.linspace(0,4,100)

y1 = x1**2+1
y2 = (x2-1.5)**2

plt.plot(x1,y1)
plt.plot(x2,y2)
plt.show()

This produces the following plot.

enter image description here

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

But instead of this, I want to plot only the minima of these two curves, i.e. only the region of y1 where y1<y2 and only the region of y2 where y2<y1. Something like this.

enter image description here

Since x1 and x2 are different, I can’t use np.minimum(). Is there an efficient way to do this with numpy and/or matplotlib?

>Solution :

You could interpolate both functions onto a common x, and then take their minimum.

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(-2, 2, 100)
x2 = np.linspace(0, 4, 100)

y1 = x1 ** 2 + 1
y2 = (x2 - 1.5) ** 2

plt.plot(x1, y1, ls=':')
plt.plot(x2, y2, ls=':')
xc = np.sort(np.concatenate([x1, x2]))
y1c = np.interp(xc, x1, y1, left=y2.max(), right=y2.max())
y2c = np.interp(xc, x2, y2, left=y1.max(), right=y1.max())

plt.plot(xc, np.minimum(y1c, y2c), lw=10, alpha=0.4)
plt.show()

taking the minimum of two functions

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