简介
Matplotlib 是 Python 中的一个数据可视化库。它提供了各种各样的工具来创建复杂且可定制的图表、图形。Matplotlib 提供的最有用的工具之一是 fill_betweenx 函数。此函数用于填充两条水平曲线之间的区域。在本教程中,我们将探索 fill_betweenx 函数,并学习如何使用它来创建不同类型的图表。
虚拟机使用提示
虚拟机启动完成后,点击左上角切换到 笔记本 标签页,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,随时向 Labby 提问。课程结束后提供反馈,我们会立即为你解决问题。
绘制简单的水平填充区域
在这一步中,我们将学习如何使用 fill_betweenx 函数来创建一个简单的图表。我们将填充两条曲线之间的区域。
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(0.0, 2, 0.01)
x1 = np.sin(2 * np.pi * y)
x2 = 1.2 * np.sin(4 * np.pi * y)
fig, ax = plt.subplots(figsize=(6, 6))
ax.fill_betweenx(y, x1, x2, color='green', alpha=0.5)
ax.plot(x1, y, color='blue')
ax.plot(x2, y, color='red')
plt.show()
创建多个子图
在这一步中,我们将学习如何创建多个子图,并使用 fill_betweenx 函数在每个子图中填充两条水平曲线之间的区域。
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(0.0, 2, 0.01)
x1 = np.sin(2 * np.pi * y)
x2 = 1.2 * np.sin(4 * np.pi * y)
fig, [ax1, ax2, ax3] = plt.subplots(1, 3, sharey=True, figsize=(12, 4))
ax1.fill_betweenx(y, 0, x1, color='green', alpha=0.5)
ax1.plot(x1, y, color='blue')
ax1.set_title('Fill between (x1, 0)')
ax2.fill_betweenx(y, x1, 1, color='red', alpha=0.5)
ax2.plot(x1, y, color='blue')
ax2.set_title('Fill between (x1, 1)')
ax3.fill_betweenx(y, x1, x2, color='orange', alpha=0.5)
ax3.plot(x1, y, color='blue')
ax3.plot(x2, y, color='red')
ax3.set_title('Fill between (x1, x2)')
plt.show()
使用逻辑条件
在这一步中,我们将学习如何使用逻辑条件来填充两条水平曲线之间的区域。
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(0.0, 2, 0.01)
x1 = np.sin(2 * np.pi * y)
x2 = 1.2 * np.sin(4 * np.pi * y)
fig, ax = plt.subplots(figsize=(6, 6))
ax.plot(x1, y, color='black')
ax.plot(x2, y, color='black')
ax.fill_betweenx(y, x1, x2, where=x2 >= x1, facecolor='green', alpha=0.5)
ax.fill_betweenx(y, x1, x2, where=x2 <= x1, facecolor='red', alpha=0.5)
plt.show()
使用掩码数组
在这一步中,我们将学习如何使用掩码数组来填充两条水平曲线之间的区域。
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(0.0, 2, 0.01)
x1 = np.sin(2 * np.pi * y)
x2 = 1.2 * np.sin(4 * np.pi * y)
x2 = np.ma.masked_greater(x2, 1.0)
fig, ax = plt.subplots(figsize=(6, 6))
ax.plot(x1, y, color='black')
ax.plot(x2, y, color='black')
ax.fill_betweenx(y, x1, x2, where=x2 >= x1, facecolor='green', alpha=0.5)
ax.fill_betweenx(y, x1, x2, where=x2 <= x1, facecolor='red', alpha=0.5)
plt.show()
总结
在本教程中,我们学习了如何使用 Matplotlib 中的 fill_betweenx 函数来填充两条水平曲线之间的区域。我们还学习了如何创建多个子图,以及如何使用逻辑条件和掩码数组来创建不同类型的图表。通过使用 fill_betweenx 函数,我们可以在 Python 中创建复杂且可定制的图表。