2

I am trying to make a fill between two datasets of different length using Matplotlib in Python. Datasets are as follows

x1 = [0.00137221, 0.01372213, 0.02607204, 0.03910806, 0.05351629,
       0.07066895, 0.08713551, 0.10634648, 0.12761578, 0.14888508,
       0.17221269, 0.19691252, 0.2271012 , 0.25797599, 0.28747856,
       0.31766724, 0.34373928, 0.36569468, 0.38559177]
y1 = [1.03307393, 1.04661479, 1.05875486, 1.07182879, 1.08723735,
       1.10544747, 1.11945525, 1.13299611, 1.14607004, 1.15540856,
       1.15680934, 1.15680934, 1.15354086, 1.14513619, 1.13346303,
       1.12085603, 1.10964981, 1.09891051, 1.08677043]
x2 = [0.00960549, 0.03773585, 0.06929674, 0.11595197, 0.15574614,
       0.18113208, 0.20994854, 0.2380789 , 0.27101201]
y2 = [1.00645914, 1.02233463, 1.03821012, 1.05315175, 1.05688716,
       1.05595331, 1.04894942, 1.04054475, 1.01579767]

I followed the procedure suggested here:

fill between two lines lacking common x values

xfill = np.linspace(0,0.4,10)
y1fill = np.interp(xfill, x1,y1)
y2fill = np.interp(xfill, x2,y2)

plt.plot(x1,y1)
plt.plot(x2,y2)
plt.fill_between(xfill, y1fill,y2fill,color = "lightgray")

When I apply the suggested code, I am getting wrong fill_between: enter image description here

Using pgfplots in LaTeX I am getting somewhat that I want enter image description here

1 Answers1

2

You can add an extra start/end point with the terminal values of the outside line:

x_start = min(x1[0], x2[0])
x_end   = max(x1[-1], x2[-1])

y_start = y1[0] if x_start == x1[0] else y2[0]
y_end   = y1[-1] if x_end == x1[-1] else y2[-1]


xfill = np.linspace(x_start, x_end, 100)
y1fill = np.interp(xfill, np.r_[x_start, x1, x_end], np.r_[y_start, y1, y_end])
y2fill = np.interp(xfill, np.r_[x_start, x2, x_end], np.r_[y_start, y2, y_end])

plt.plot(x1,y1)
plt.plot(x2,y2)
plt.fill_between(xfill, y1fill, y2fill, color="lightgray")

Output:

diagonal fill between

As a function:

def fill_between_ends(x1, x2, y1, y2, **kwargs):
    x_start = min(x1[0], x2[0])
    x_end   = max(x1[-1], x2[-1])

    y_start = y1[0] if x_start == x1[0] else y2[0]
    y_end   = y1[-1] if x_end == x1[-1] else y2[-1]

    xfill = np.linspace(x_start, x_end,100)
    y1fill = np.interp(xfill, np.r_[x_start, x1, x_end], np.r_[y_start, y1, y_end])
    y2fill = np.interp(xfill, np.r_[x_start, x2, x_end], np.r_[y_start, y2, y_end])

    plt.fill_between(xfill, y1fill, y2fill, **kwargs)
   
plt.plot(x1,y1)
plt.plot(x2,y2)
fill_between_ends(x1, x2, y1, y2, color="lightgray")
mozway
  • 194,879
  • 13
  • 39
  • 75