2

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

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?

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.

1
  • So you want some kind of piece-wise function e.g y1 for x<0.5 else y2? You write that you want to plot the minima of both functions but it is not what you are plotting ? Commented Nov 16, 2021 at 11:43

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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:

piece-wise function

2 Comments

This works for this specific case, but I also want a solution that is more general; one that works when I don't define y1 and y2 myself through a known function, but extract them from a dataset instead.
@TheOne I see, you should have mentioned it, I'd have proposed a different approach ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.