How to fill the region between several curves in python?

Viewed 177

How to fill with colour the region between four curves in this code, please? Two of them is a connection between two points. I tried the following script. The last but one row is wrong.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

x_shift = 140.5
b = 50
const = 28.3

fig, ax = plt.subplots()
plt.rcParams["figure.figsize"] = [10, 3]

r = np.sqrt(36000)
theta_zoom1 = np.linspace(-0.14*np.pi, 0, 10000)
x1_zoom1 = r*np.cos(theta_zoom1) - x_shift
x2_zoom1 = r*np.sin(theta_zoom1) + b
theta_zoom2 = np.linspace(-0.156*np.pi, 0, 10000)
x1_zoom2 = r*np.cos(theta_zoom2) - x_shift
x2_zoom2 = r*np.sin(theta_zoom2) + b

ax.plot(x1_zoom1 + const, x2_zoom1)
ax.plot(x1_zoom2 + 3*const, x2_zoom2)

plt.plot([60, 130],[-9.2, -9.2])
plt.plot([70, 140],[35.7, 35.7])

ax.fill_between(x2_zoom1, x2_zoom2)

plt.show()

Wrong result:

enter image description here

The desired result: enter image description here

1 Answers

You can use ax.fill_betweenx() to fill the region. This needs a common array of y-values and two arrays of corresponding x-values. np.interp() can be used to match the existing curves to the new y-values. Note that the given y-values need to be in strict increasing order for this to work.

import numpy as np
import matplotlib.pyplot as plt

x_shift = 140.5
b = 50
const = 28.3

fig, ax = plt.subplots()
plt.rcParams["figure.figsize"] = [10, 3]

r = np.sqrt(36000)
theta_zoom1 = np.linspace(-0.14 * np.pi, 0, 10000)
x1_zoom1 = r * np.cos(theta_zoom1) - x_shift
x2_zoom1 = r * np.sin(theta_zoom1) + b
theta_zoom2 = np.linspace(-0.156 * np.pi, 0, 10000)
x1_zoom2 = r * np.cos(theta_zoom2) - x_shift
x2_zoom2 = r * np.sin(theta_zoom2) + b

ax.plot(x1_zoom1 + const, x2_zoom1)
ax.plot(x1_zoom2 + 3*const, x2_zoom2)

ax.plot([60, 130], [-9.2, -9.2])
ax.plot([70, 140], [35.7, 35.7])

y_fill = np.linspace(-9.2, 35.7, 200)
x_fill1 = np.interp(y_fill, x2_zoom1, x1_zoom1 + const)
x_fill2 = np.interp(y_fill, x2_zoom2, x1_zoom2 + 3*const)

ax.fill_betweenx(y_fill, x_fill1, x_fill2, color='crimson', alpha=0.3)

plt.show()

resulting plot

Related