Reputation: 3
I want to fill the area between two non-linear curves with some color, say "grey". There should not be any separation line within the shaded region. Also, the shaded region should be within the limit of the lower and upper bounds.
I have tried with the fill_between
function, but as you can see in the figure, it has an extra line in it, and extends above the upper bound.
Could anyone help me to fix this problem? I have tried like:
plt.fill_betweenx(Y_upper, X_upper, X_lower, color='grey', alpha = 0.2)
plt.fill_between(X_lower, Y_upper, Y_lower, color='grey', alpha = 0.2)
Where X_lower
and Y_lower
represent the lower curve (curve in orange) and X_upper
and Y_upper
show the upper curve (green curve).
Upvotes: 0
Views: 364
Reputation: 80459
For fill_between(x, y1, y2)
to work, both y1
and y2
need to be calculated over the same x-range. You could create a new array of x-values containing the x-values of both curves, in sorted order. And then use np.interp
to recalculate the y-values of both curves.
Easier is to concatenate the reverse of the second curve to the first, which would create a closed polygon. plt.fill
can than color that polygon.
The strange bump you see, are the y-values of the upper curve combined by the x-values of the shorter lower curve.
Here is an example to illustrate the idea:
from matplotlib import pyplot as plt
import numpy as np
x_upper = np.linspace(-330, 40, 200)
y_upper = (40 - x_upper) * (x_upper + 330)
x_lower = np.linspace(-220, 20, 200)
y_lower = (20 - x_lower) * (x_lower + 220)
plt.plot(x_upper, y_upper, color='darkgreen')
plt.plot(x_lower, y_lower, color='orange')
plt.fill(np.append(x_upper, x_lower[::-1]), np.append(y_upper, y_lower[::-1]), color='black', alpha=0.1)
plt.plot(x_lower, y_upper, color='navy', ls='--', lw=0.5) # this is the strange curve seen
plt.show()
Upvotes: 1