用python 画几个简单图案

1 turtle

turtle这个库真的很好玩,用很简单几行代码就能画出好看的图案,最近无聊翻了翻之前自己画的哈哈哈哈,分享几个代码 画一个类似五颜六色的棒棒糖图案

import turtle  
turtle.pensize(5)  # 这里建议笔的粗细设置的更细一点,太粗了不太好看
color = ['orange','blue','yellow','black','green','tomato']  # 设置自己喜欢的几个颜色
for i in range(600):  # 让接下来的代码循环多少次,600次就够了,要是前面加入初始化,把画布设置的大一点可以设置次数更多
    turtle.pencolor(color[i%6])   #  因为设置了六个颜色,要是想基于其他形状的,记得有多少条边设置多少个颜色,这里取余也要调整
    turtle.fd(i*1.15)  # 可以自己去搜搜递增类型的函数 ,这里简单设置一个
    turtle.left(62)   # 我是基于正6变形画,每次左转60度,但是为了有交叉感,稍微增大几度

好了,看看这个的结果

2 利用matplotlib.pyplot画一个随机漫步

from random import choice  # random 的choice方法能够在你给出的结果里随机选择一个
import matplotlib.pyplot as plt  # 引入matplotlib

class Random_walk():
    def __init__(self,num_points=5000):
        """一个生成随机漫步数据的类"""
        self.num_points = num_points  #  初始化,先将x,y值都设置为0,同时需要自己设置行程多少个点(num_points)
        self.x_values = [0]
        self.y_values = [0]
    def fill_walk(self):
        while len(self.x_values) < self.num_points: # 设置循环到num_points次
            x_direction = choice([1,-1]) # x y 轴因为都有正负方向,随机选择前进方向以及距离
            x_distance = choice([0,1,2,3,4])
            x_step = x_direction * x_distance 

            y_direction = choice([1,-1])
            y_distance = choice([0,1,2,3,4])
            y_step = y_direction * y_distance

            if x_step == 0 and y_step ==0:
                continue
            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step
            self.x_values.append(next_x)
            self.y_values.append(next_y)
    def scatter(self):
            plt.scatter(self.x_values,self.y_values,s=5)
            
            plt.show()
            
mx = Random_walk()
mx.fill_walk()
mx.scatter()

2 例子的代码其实很简单,我自己比较懒,不喜欢写注释,直接看下结果吧

猜你喜欢

转载自www.cnblogs.com/oslo254804746/p/11864454.html