实验要求:
利用python绘制递归正六边形,递归层数需要可以自选
吐槽,matplotlib绘制线段参数必须是下x,y,真的是巨坑
代码如下:
import matplotlib.pyplot as plt#约定俗成的写法plt
import numpy as np
import math
num = int(input("please input the number of recursion:"))
# num = 5
plt.figure()
plt.xlim(0,800) #x轴坐标轴
plt.ylim((0, 600))#y轴坐标轴
plt.xlabel('X')#x轴标签
plt.ylabel('Y')#y轴标签
# give the pot of regular hexagon
distance = 150*math.sqrt(3)
x = [300,600,750,600,300,150,300]
y = [0,0,distance,2*distance,2*distance,distance,0]
num -= 1
plt.plot(x,y, color='#FF0000')
dataX = x
dataY = y
while num > 0:
num -= 1
demoX = [abs(dataX[i] + dataX[i+1])/2 for i in range(6)]
demoY = [abs(dataY[i] + dataY[i+1])/2 for i in range(6)]
dataX = demoX
dataX.append(demoX[0])
dataY = demoY
dataY.append(demoY[0])
x = dataX
y = dataY
plt.plot(x,y, color='#FF0000',) #注意这里必须是x,y,所以我的上一步做了一个赋值操作
plt.show()
演示效果如下: