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.
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.
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?
I would like to have a general approach that also works when y1 and y2 are not determined from some function I know, but are taken from e.g. a dataset.
CodePudding user response:
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()
CodePudding user response:
One solution is to cross compute the functions with the other xs and mask:
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
y1b = x2**2 1
y2 = (x2-1.5)**2
y2b = (x1-1.5)**2
plt.plot(x1, np.where(y1<y2b, y1, np.nan))
plt.plot(x2, np.where(y2<y1b, y2, np.nan))
plt.show()
output: