简介
本教程将向你展示如何使用 Python 的 Matplotlib 包创建一个使用弧度的图表。你将学习如何使用单位类来确定刻度定位、格式化和轴标签。
虚拟机提示
虚拟机启动完成后,点击左上角切换到“笔记本”标签,以访问 Jupyter Notebook 进行练习。
有时,你可能需要等待几秒钟让 Jupyter Notebook 完成加载。由于 Jupyter Notebook 的限制,操作验证无法自动化。
如果你在学习过程中遇到问题,请随时向 Labby 提问。课程结束后提供反馈,我们将立即为你解决问题。
导入必要的包
首先,导入必要的包,包括 matplotlib.pyplot 和 numpy。
import matplotlib.pyplot as plt
import numpy as np
创建数据
创建一个从 0 到 15(步长为 0.01)的数值数组,并使用 basic_units 包中的 radians 函数将它们转换为弧度。
from basic_units import radians
x = [val*radians for val in np.arange(0, 15, 0.01)]
创建一个图形
使用 matplotlib.pyplot 中的 subplots 函数创建一个包含两个子图的图形。
fig, axs = plt.subplots(2)
在第一个子图中绘制数据
使用 matplotlib.pyplot 中的 plot 函数,在第一个子图中绘制 x 值的余弦值。使用 xunits 参数指定 x 轴应以弧度为单位。
from basic_units import cos
axs[0].plot(x, cos(x), xunits=radians)
在第二个子图中绘制数据
使用 matplotlib.pyplot 中的 plot 函数,在第二个子图中绘制 x 值的余弦值。使用 xunits 参数指定 x 轴应以度为单位。
from basic_units import degrees
axs[1].plot(x, cos(x), xunits=degrees)
添加标签并调整布局
使用 matplotlib.pyplot 中的 title、xlabel 和 ylabel 函数为子图添加标题和轴标签。使用 tight_layout 函数调整子图的布局。
axs[0].set_title('Cosine with Radian X-Axis')
axs[0].set_xlabel('Radians')
axs[0].set_ylabel('Cosine')
axs[1].set_title('Cosine with Degree X-Axis')
axs[1].set_xlabel('Degrees')
axs[1].set_ylabel('Cosine')
fig.tight_layout()
显示图形
使用 matplotlib.pyplot 中的 show 函数显示图形。
plt.show()
总结
在本教程中,你学习了如何使用 Python 的 Matplotlib 包创建一个以弧度为单位的绘图。你使用了单位类来确定刻度定位、格式化和轴标签。你还学习了如何创建子图、绘制数据、添加标签以及调整绘图的布局。