📜  如何在 Matplotlib 中的多行之间填充?

📅  最后修改于: 2022-05-13 01:54:58.033000             🧑  作者: Mango

如何在 Matplotlib 中的多行之间填充?

使用fill_between()  使用Python中 Matplotlib 库中的函数,我们可以轻松地填充二维平面上任意多条线或任意两条水平曲线之间的颜色。

示例 1:数学函数f(x)=sin(x)曲线之间的颜色

Python3
import pylab as plt
import numpy as np
 
x = np.arange(0.0, 2, 0.01)
y1 = np.sin(2 * np.pi * x)
y2 = 0.8 * np.sin(4 * np.pi * x)
 
fig, (ax1, ax2, ax3) = plt.subplots(
  3, 1, sharex=True, figsize=(6, 6))
 
ax1.fill_between(x, y1)
ax1.set_title('fill between y1 and 0')
 
ax2.fill_between(x, y1, 1)
ax2.set_title('fill between y1 and 1')
 
ax3.fill_between(x, y1, y2)
ax3.set_title('fill between y1 and y2')
ax3.set_xlabel('x')
fig.tight_layout()


Python3
import pylab as plt
import numpy as np
 
X = np.linspace(0, 3, 200)
Y1 = X**2 + 3
Y2 = np.sin(X)
Y3 = np.cos(X)
 
plt.plot(X, Y1, lw=4)
plt.plot(X, Y2, lw=4)
plt.plot(X, Y3, lw=4)
 
plt.fill_between(X, Y1, Y2, color='k', alpha=.5)
plt.fill_between(X, Y1, Y3, color='y', alpha=.5)
 
plt.show()


Python3
import matplotlib.pyplot as plt
 
 
x = [1, 2, 1, 0]
y = [2, 1, 0, 1]
 
plt.fill(x, y)
plt.show()


输出:

示例 2:数学函数f(x)=cos(x) 和 f(x)=exp(x)曲线之间的颜色:-

蟒蛇3

import pylab as plt
import numpy as np
 
X = np.linspace(0, 3, 200)
Y1 = X**2 + 3
Y2 = np.sin(X)
Y3 = np.cos(X)
 
plt.plot(X, Y1, lw=4)
plt.plot(X, Y2, lw=4)
plt.plot(X, Y3, lw=4)
 
plt.fill_between(X, Y1, Y2, color='k', alpha=.5)
plt.fill_between(X, Y1, Y3, color='y', alpha=.5)
 
plt.show()

输出:

示例 3:菱形着色:-

蟒蛇3

import matplotlib.pyplot as plt
 
 
x = [1, 2, 1, 0]
y = [2, 1, 0, 1]
 
plt.fill(x, y)
plt.show()

输出: