1

How do I fill the color between two curves? I want to fill the area bounded by the curve above the horizontal line with one color, and the area bounded by the curve below the horizontal line with a second different color..

random_x = [-180, -160, -140, -100, -70, -40, -10, 20, 50, 80, 110, 120, 140, 165,175, 180]
random_y = [2000000, 700000, 2800000, 4200000, 1000000, 1200000, 3500000, 2000000, 800000, 3900000, 2500000, 1000000,3400000,2400000,2100000, 2000000]

interp1d_cubic = interp1d(random_x, random_y, kind='cubic')
x3 = np.linspace(-180, 180, 100000)
plt.plot(x3, interp1d_cubic(x3), c='k')
y_coord = np.linspace(980000,980000,100000)
plt.plot(x3, y_coord, c='k', linestyle='--')
plt.show()

The resulting current plot looks as follows:

enter image description here

JakobVinkas
  • 1,003
  • 7
  • 23
chelseabej1998
  • 111
  • 1
  • 6
  • This is not strictly speaking the same task. On the older answer, it is about filling between 3 lines, but only a single colour for each pair. On this one, it is requested to fill a pair with different colours. There is a way of doing it: ... y_inter = interp1d_cubic(x3) # not to call it all the time plt.plot(x3, y_inter, c='k') ... plt.fill_between(x3,y_coord,y_inter, where = y_coord > y_inter, color = "blue") plt.fill_between(x3,y_coord,y_inter, where = y_coord <= y_inter, color = "green") ... This uses the fill_between with the "where" option to select a specified region. – fdireito Jun 30 '20 at 16:10

1 Answers1

0

This is definetly not a perfect way but it does work. Simply plot lines between the two points on the lines in the specified color. Then you can change the width of the lines and the spacing of the lines to "fill" the area between them while keeping a good enough resolution.

import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
import numpy as np

random_x = [-180, -160, -140, -100, -70, -40, -10, 20, 50, 80, 110, 120, 140, 165,175, 180]
random_y = [2000000, 700000, 2800000, 4200000, 1000000, 1200000, 3500000, 2000000, 800000, 3900000, 2500000, 1000000,3400000,2400000,2100000, 2000000]

interp1d_cubic = interp1d(random_x, random_y, kind='cubic')
x3 = np.linspace(-180, 180, 100000)
plt.plot(x3, interp1d_cubic(x3), c='k')
y_coord = np.linspace(980000,980000,100000)
plt.plot(x3, y_coord, c='k', linestyle='--')

# Variable names changed for convenience
y1 = interp1d_cubic(x3)
y2 = y_coord
x = x3
# With default linewidth, plotting a line at every
# 200th point was just fine
for i in range(0,len(x3),200):
    if y1[i] > y2[i]:
        c = 'r'
    else:
        c = 'b'
    plt.plot([x[i],x[i]], [y1[i], y2[i]], color = c, zorder=0)

plt.show()

Which gives the following result:

enter image description here

If you are simply looking for a visual representation and time complexity is not an issue, this should do just fine.

JakobVinkas
  • 1,003
  • 7
  • 23