I have this tiny problem with a chart I am working on. I\'d like to fill the area between 2 semi-vertical lines as shown below (teal and grey ones):
However, when I use
The data ranges of the x variable of both lines are completely seperate, so there is not even a single point at which a fill could be done in y direction.
You may want to fill in x direction instead, which could be done using fill_betweenx
. The problem is now that the y values of both lines are different. One would therefore need to interpolate them such that the fill_betweenx
can use the same y values for the fill between the two curves that initially have different y values for different x values.
import numpy as np
import matplotlib.pyplot as plt
x1 = np.array([1.00, 1.20, 1.30, 1.55, 1.60])
x2 = np.array([1.82, 1.91, 2.14, 2.26, 2.34])
y1 = np.array([1.03, 1.20, 1.28, 1.42, 1.71])
y2 = np.array([0.90, 1.10, 1.31, 1.42, 1.58])
fig, ax= plt.subplots()
ax.plot(x1,y1, color="indigo")
ax.plot(x2,y2, color="crimson")
yi = np.sort(np.c_[y1,y2].flatten())
x1i = np.interp(yi, y1, x1)
x2i = np.interp(yi, y2, x2)
ax.fill_betweenx(yi, x1i, x2i, color="lemonchiffon")
plt.show()
The alternative to the above solution could be to draw a polgon, with the coordinates of both lines as its edge points.
import numpy as np
import matplotlib.pyplot as plt
x1 = np.array([1.00, 1.20, 1.30, 1.55, 1.60])
x2 = np.array([1.82, 1.91, 2.14, 2.26, 2.34])
y1 = np.array([1.03, 1.20, 1.28, 1.42, 1.71])
y2 = np.array([0.90, 1.10, 1.31, 1.42, 1.58])
fig, ax= plt.subplots()
ax.plot(x1,y1, color="indigo")
ax.plot(x2,y2, color="crimson")
x = np.append(x1,x2[::-1])
y = np.append(y1,y2[::-1])
p = plt.Polygon(np.c_[x,y], color="lemonchiffon")
ax.add_patch(p)
plt.show()