Fill area between a curve and diagonal lines

Question:

Could you please help me with this issue.
I was wondering how to fill the area between a curve and diagonal line (a line that connect the (X min, Y min) to (X max, Y max). For example, in the following plot how we can fill the area above diagonal line red and the area below blue. In advance, I appritiate your time and consideration.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize = (6,4))
x=np.array([0,1,2,3,4,5,6,7,8,9,10])
y=np.array([0,4,5,5,4,5,6,8,9,9,15])

ax.plot(x,y, color = "red", lw=1.2)
ax.plot([x.min(),x.max()],[y.min(),y.max()], color = "black", lw=1.2)

plt.show()
Asked By: Jab

||

Answers:

The fill_between() method is designed especially for that:

# Create empty figure 
_,ax = plt.subplots()
# Plot the two lines
ax.plot(x,x,color='C0')
ax.plot(x,y,color='C3')
# Plot the area with two conditions (x>y) and (x<=y)
ax.fill_between(x, x, y, where=(x > y), color='C0', alpha=0.2,
                 interpolate=True)
ax.fill_between(x, x, y, where=(x <= y), color='C3', alpha=0.2,
                 interpolate=True)

And we obtain:

enter image description here

Answered By: obchardon

Thanks obchardon. I could do it. I fitted a linear regression model with the [x.min(),x.max()],[y.min(),y.max()] to define the diagonal line and then fill the area between the curve with the diagonal.

import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize = (6,4))
x=np.array([0,1,2,3,4,5,6,7,8,9,10])
y=np.array([0,4,5,5,4,5,6,8,9,9,15])

ax.plot(x,y, color = "red", lw=1.2)
(m,b)=np.polyfit([x.min(),x.max()] ,[y.min(),y.max()] ,1)
yp = np.polyval([m,b],x)
plt.plot(x,yp, color='black',lw=1)
ax.fill_between(x,y, yp, where=(y > yp), color='red',interpolate=True)
ax.fill_between(x, y, yp, where=(y <= yp), color='blue',interpolate=True)
plt.show()
Answered By: Jab