问题
I need to fill space between 3 graphs but I don't understand how to limit the area on the graph y2
import numpy as np
import matplotlib.pyplot as plt
y = lambda z: (4 * z - z ** 2) ** (1 / 2)
y1 = lambda x: (8 * x - x ** 2) ** (1 / 2)
y2 = lambda c: c * 3 ** (1 / 2)
x = np.linspace(0, 12, 100)
z = np.linspace(0, 12, 100)
c = np.linspace(0, 12, 100)
plt.ylim(0, 4)
plt.xlim(0, 4)
plt.plot(z, y(z), color='blue', label="y=(18-x^2)^(1/2)")
plt.plot(c, y2(c))
plt.plot(x, y1(x), color='red', label='y=3*2^(1/2) - (18-x^2)^(1/2)')
plt.grid(True, zorder=5)
plt.fill_between(x, y(z), y1(x), alpha=0.5)
plt.show()
回答1:
To fill the space that is both above y
and above y2
, you can take the maximum of both. In order to only fill where y1
is above y2
, you can you the where
parameter:
plt.fill_between(x, np.maximum(y(z), y2(c)), y1(x), where=y2(c)<=y1(x), alpha=0.5)
You might need to use more than 100 points in the linspace
s to avoid small regions without filling. For this image I used np.linspace(0, 12, 500)
.
To have nicer labels, you could you latex format (enclose with $ signs, and add braces for the powers):
plt.plot(..., label="$y=(18-x^2)^{1/2}$")
plt.plot(..., label='$y=3*2^{1/2} - (18-x^2)^{1/2}$')
To get a square root symbol, use the latex function \sqrt
. To have a backslash in a Python string, either the backslash should be doubled, or the string should be preceded by an r
(raw string).
plt.plot(..., label="$y=\\sqrt{18-x^2}$")
plt.plot(..., color='red', label='$y=3*\\sqrt{2} - \\sqrt{18-x^2}$')
来源:https://stackoverflow.com/questions/60782232/how-to-fill-space-to-border-with-in-matplotlib