在这篇文章中,你将学习如何使用Matplotlib来绘制一条简单的正弦曲线,显示角度和正弦函数值之间的关系。
1.如何使用Python Matplotlib绘制一条简单的正弦曲线步骤
-
首先,导入Matplotlib包中的Pyplot模块,并以asalias的形式简化导入包的名称。
import matplotlib.pyplot as plt -
接下来,使用NumPy提供的函数range(),创建一组数据来绘制图像。
# import numpy library. import numpy as np # get the ndarray object between 0 and 2π. x = np.arange(0, math.pi*2, 0.05) -
上面得到的X的值就是X轴上的值,用下面的方法得到与这个值相对应的正弦值,也就是Y轴的值。
y = np.sin(x) -
使用plot()函数绘制正弦曲线的X和Y值。
plt.plot(x,y) -
主要的绘制工作已经完成,但我们还需要绘制一些细节,这些细节需要补充,如x轴和y轴的标签,图像的标题等。
# plot the x, y label. plt.xlabel("angle") plt.ylabel("sine") # plot the image title. plt.title('sine wave') -
完整的示例程序代码如下:
# import matplotlib pyplot module. from matplotlib import pyplot as plt # import numpy module. import numpy as np # import python math module. import math # call the math.pi method to convert radians to angles. # get the x-axis value. x = np.arange(0, math.pi*2, 0.05) # calculate the y-axis value use the np.sin() method. y = np.sin(x) # plot the sine curve. plt.plot(x,y) # draw the x-axis and y-axis label. plt.xlabel("angle") plt.ylabel("sine") # draw the image title. plt.title('sine wave') # call the show() method to display the image. plt.show() -
当你运行上述例子的源代码时,你会得到下面的正弦曲线图像。