python3的turtle绘图库是python自带的,类似GDI绘图,其中setup函数是设置窗口大小,
up()是抬笔,down()是落笔,setposition()设置当前笔在位置,坐标系原点为屏幕中心,可以通过setworldcoordinates(左下角,右上角)来重新设置世界原点,
tracer(False) 关闭动画。当down()以后,setposition的方式画线,下面就是包装了一些turtle的api实现的drawLine, 并绘制了一个直角xy坐标系, 然后将
sin(x), 0 <=x && x <= 2pi区间的正弦曲线以多段线离散可视化出来的,曲线在x和y方向上进行了缩放,以方便观察
import turtle as t import math as mt def drawLine(x0,y0,x1,y1): t.up() t.setposition(x0,y0) t.down() t.setposition(x1,y1) t.up() def drawText(s, posx, posy): t.up() t.goto(posx, posy) t.down() t.write(s, font=("Arial",10,"normal")) t.up() def drawXAxis(x0,y0,axTailLength, arrowWidth, arrowHeight): drawLine(x0,y0,x0+axTailLength+arrowHeight,y0) halfw = arrowWidth*0.5 drawLine(x0+axTailLength,y0-halfw, x0+axTailLength,y0+halfw) drawLine(x0+axTailLength,y0-halfw, x0+axTailLength+arrowHeight,y0) drawLine(x0+axTailLength,y0+halfw, x0+axTailLength+arrowHeight,y0) drawText("X", x0+axTailLength+arrowHeight,y0) def drawYAxis(x0,y0,axTailLength, arrowWidth, arrowHeight): drawLine(x0,y0,x0,y0+axTailLength+arrowHeight) halfw = arrowWidth*0.5 drawLine(x0-halfw,y0+axTailLength, x0+halfw,y0+axTailLength) drawLine(x0-halfw,y0+axTailLength, x0,y0+axTailLength+arrowHeight) drawLine(x0+halfw,y0+axTailLength, x0,y0+axTailLength+arrowHeight) drawText("Y", x0,y0+axTailLength+arrowHeight) t.setup(500, 400) t.tracer(False) t.setworldcoordinates(-100, -150, 400, 250) drawXAxis(-20,0,350,10,10) drawYAxis(0,-20,200,10,10) n = 40 dsi = (2.0 * mt.pi) / float(n) ptsX = [] ptsY = [] for i in range(n+1): si = dsi * float(i) ptsX.append(int(si*40.0+0.5)) sinsi = mt.sin(si) ptsY.append(int(sinsi*100.0+0.5)) t.color("green") t.pensize(2) for i in range(1,n+1): drawLine(ptsX[i-1], ptsY[i-1], ptsX[i], ptsY[i]) t.done()
© 著作权归作者所有
举报
发表评论
0/200