python绘制笛卡尔直角坐标系
背景完整代码代码解读
背景
有些数学题目经常要用到数形结合思想,尤其是一些函数题目,如果能够把函数图像画出来进行解题的话,思路会更加清晰明了。python绘图主要用到matplotlib绘图模块,平时我们看到的往往是下面这种图 用一个实线矩形把几何图形封闭起来,看起来好像在一个象限里面。现实中,我们通常采用描点作图,首先建立一个笛卡尔直角坐标系,然后根据一个自变量,一个因变量的在坐标系里面描一些点,然后用一条光滑曲线把这些点串起来,更像下面这种图
那么,我们怎么才能利用matplotlib模块画出上面的正弦函数呢?先看代码,再听分解
完整代码
"""
Created on Fri Nov 1 20:39:16 2019
project name:plot sine function image with python
@author: 帅帅de三叔
"""
import math
import numpy
as np
import matplotlib
.pyplot
as plt
import mpl_toolkits
.axisartist
as axisartist
fig
=plt
.figure
(figsize
=(4,2))
ax
=axisartist
.Subplot
(fig
,111)
fig
.add_axes
(ax
)
ax
.axis
[:].set_visible
(False)
ax
.axis
["x"]=ax
.new_floating_axis
(0,0,axis_direction
="bottom")
ax
.axis
["y"]=ax
.new_floating_axis
(1,0,axis_direction
="bottom")
ax
.axis
["x"].set_axisline_style
("->",size
=1.0)
ax
.axis
["y"].set_axisline_style
("->",size
=1.0)
ax
.annotate
(s
='x' ,xy
=(2*math
.pi
,0) ,xytext
=(2*math
.pi
,0.1))
ax
.annotate
(s
='y' ,xy
=(0,1.0) ,xytext
=(-0.5,1.0))
plt
.xlim
(-6.3,6.3)
plt
.ylim
(-1.1,1.1)
ax
.set_xticks
([-2*math
.pi
,-math
.pi
,0,math
.pi
,2*math
.pi
])
ax
.set_yticks
([-1,1])
y
=[]
x
=np
.linspace
(-2*math
.pi
,2*math
.pi
,100)
for xi
in x
:
y
.append
(math
.sin
(xi
))
plt
.plot
(x
,y
,color
="blue")
plt
.show
()
代码解读
工欲善其事必先利其器,画坐标轴当然要用到坐标轴加工类 axisartist,接下来就是用匠心精神不断打磨坐标轴。
首先,隐藏原来的实线矩形
ax
.axis
[:].set_visible
(False)
其次,添加自定义x轴和y轴
ax
.axis
["x"]=ax
.new_floating_axis
(0,0,axis_direction
="bottom")
ax
.axis
["y"]=ax
.new_floating_axis
(1,0,axis_direction
="bottom")
接着,加箭头,设置箭头款式,并把坐标轴标注出来
ax
.axis
["x"].set_axisline_style
("->",size
=1.0)
ax
.axis
["y"].set_axisline_style
("->",size
=1.0)
ax
.annotate
(s
='x' ,xy
=(2*math
.pi
,0) ,xytext
=(2*math
.pi
,0.1))
ax
.annotate
(s
='y' ,xy
=(0,1.0) ,xytext
=(-0.5,1.0))
修缮刻度和范围
plt
.xlim
(-6.3,6.3)
plt
.ylim
(-1.1,1.1)
ax
.set_xticks
([-2*math
.pi
,-math
.pi
,0,math
.pi
,2*math
.pi
])
ax
.set_yticks
([-1,1])
到这里,一个比较好看的正弦函数图像才算画出来,逻辑上来说,要使得坐标轴的标注位置恰当,加标注操作应该在设置坐标轴范围操作之后。
延伸阅读 python画三维爱心