1.
from turtle import *
from random import randint
width,height = 480,360
screen = Screen()
screen.setup(width,height)
screen.title("python海龟画图的彩色粒子效果_作者:邹明志")
screen.bgcolor("black")
screen.colormode(255)
screen.delay(0)
class Particle(Turtle):
def __init__(self):
Turtle.__init__(self,visible=False,shape="circle")
self.penup()
self.speed(0)
c = (randint(0,255),randint(0,255),randint(0,255))
self.color(c,c)
self.shapesize(0.1,0.1) #形状为1/10
self.accspeed = -0.1 #加速度
self.initmove() #初始化移动
def initmove(self):
self.goto(0,0)
self.xspeed = randint(-2,2)
self.yspeed = randint(3,5)
self.showturtle()
self.move()
def move(self):
x = self.xcor() + self.xspeed #水平方向移动
y = self.ycor() + self.yspeed #垂直方向受重力移动
if y>-height/2: #没到屏幕最下面,那么就移动到新位置
self.yspeed = self.yspeed + self.accspeed
self.goto(x,y)
screen.ontimer(self.move,10)
else:
self.hideturtle() #隐藏粒子
self.initmove() #继续移到(0,0)坐标,重生.
if __name__=="__main__":
p = []
for i in range(60):
p.append(Particle())
screen.mainloop()
2.
#f(x,y) = x^2 + y^2 + x
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D#导入该函数是为了绘制3D图
import matplotlib as mpl
#########
#将数据绘图出来
#生成X和Y的数据
X = np.arange(-5,5,0.1) #-5到5的等距数组,距离为0.1,注意区分开range(),它返回的是一个列表
Y = np.arange(-5,5,0.1)
X,Y = np.meshgrid(X,Y)#该函数用来生成网格点坐标矩阵。
#目标函数
Z = X**2 + Y**2 + X
#绘图
fig = plt.figure()#创立一个画布
ax = Axes3D(fig)#在这个画布里,生成一个三维的空间
surf = ax.plot_surface(X,Y,Z,cmap=cm.coolwarm)#该函数是为了将数据在这三维空间里可视化出来。
plt.show()
###########
#######
#计算适应度,这里的适应度就是我们目标函数Z的值,因为我们要求Z的最小值。
#这两个函数,一般使用mpl画图的时候都会用到
mpl.rcParams['font.sans-serif'] = ['SimHei']# 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'无法显示的问题
#使用matplotliblib画图的时候经常会遇见中文或者是负号无法显示的情况
#rcParams函数里的参数可以修改默认的属性,包括窗体大小、每英寸的点数、线条宽度、颜色、样式、坐标轴、坐标和网络属性、文本、字体等
def fitness_func(X):
x = X[:,0]
y = X[:,1]
return x**2 + y**2 + x
##########
#############
#更新速度,根据公式V(t+1)=w*V(t)+c1*r1*(pbest_i-xi)+c1*r1*(gbest_xi)
def velocity_update(V,X,pbest,gbest,c1,c2,w,max_val):
size = X.shape[0]#返回矩阵X的行数
r1 = np.random.random((size,1))#该函数表示成size行 1列的浮点数,浮点数都是从0-1中随机。
r2 = np.random.random((size,1))
V = w*V + c1*r1*(pbest-X)+c2*r2*(gbest-X)#注意这里得到的是一个矩阵
#这里是一个防止速度过大的处理,怕错过最理想值
V[V<-max_val] = -max_val
V[V>-max_val] = max_val
return V
#########
########
#更新粒子位置,根据公式X(t+1)=X(t)+V
def position_updata(X,V):
return X+V
##########
#########
def pos():
w = 1 #设置惯性权重
c1 = 2 #设置个体学习系数
c2 = 2 #设置全局学习系数
r1 = None
r2 = None
dim = 2
size = 20 #这里是初始化粒子群,20个
iter_num = 1000 #迭代1000次
max_val = 0.5 #限定最大速度为0.5
best_fitness = float(9e10) #初始化适应度的值
fitness_val_list = []
#初始化各个粒子的位置
X = np.random.uniform(-5,5,size=(size,dim))
#初始化各个粒子的速度
V = np.random.uniform(-0.5,0.5,size=(size,dim))
p_fitness = fitness_func(X)#得到各个个体的适应度值
g_fitness = p_fitness.min()#全局最理想的适应度值
fitness_val_list.append(g_fitness)
pbest = X#初始化个体的最优位置
gbest = X[p_fitness.argmin()]#初始化整个整体的最优位置
#迭代
for i in range(1,iter_num):
V = velocity_update(V, X, pbest, gbest, c1, c2, w, max_val)
X = position_updata(X,V)
p_fitness2 = fitness_func(X)
g_fitness2 = p_fitness2.min()
#更新每个粒子的历史的最优位置
for j in range(size):
if p_fitness[j] > p_fitness2[j]:
pbest[j] = X[j]
p_fitness[j] = p_fitness2[j]
if g_fitness > g_fitness2:
gbest = X[p_fitness2.argmin()]
g_fitness = g_fitness2
fitness_val_list.append(g_fitness)
i += 1
print("最优值是:%.5f" % fitness_val_list[-1])
print("最优解是:x=%.5f,y=%.5f" % (gbest[0],gbest[1]))
plt.plot(fitness_val_list,c='r')
plt.title('迭代过程')
plt.show()
#########
if __name__ == '__main__':
pos()
3.
# importing the required module
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3]
# corresponding y axis values
y = [2,4,1]
# plotting the points
plt.plot(x, y)
# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
# giving a title to my graph
plt.title('My first graph!')
# function to show the plot
plt.show()
4.
import matplotlib.pyplot as plt
# line 1 points
x1 = [1,2,3]
y1 = [2,4,1]
# plotting the line 1 points
plt.plot(x1, y1, label = "line 1")
# line 2 points
x2 = [1,2,3]
y2 = [4,1,3]
# plotting the line 2 points
plt.plot(x2, y2, label = "line 2")
# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
# giving a title to my graph
plt.title('Two lines on same graph!')
# show a legend on the plot
plt.legend()
# function to show the plot
plt.show()
5.
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3,4,5,6]
# corresponding y axis values
y = [2,4,1,5,2,6]
# plotting the points
plt.plot(x, y, color='green', linestyle='dashed', linewidth = 3,marker='o', markerfacecolor='blue', markersize=12)
# setting x and y axis range
plt.ylim(1,8)
plt.xlim(1,8)
# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
# giving a title to my graph
plt.title('Some cool customizations!')
# function to show the plot
plt.show()
6.
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)#x轴上的点,0到2之间以0.01为间隔
s = np.sin(2*np.pi*t)#y轴为正弦
plt.plot(t, s)#画图
plt.xlabel('time (s)')#x轴标签
plt.ylabel('voltage (mV)')#y轴标签
plt.title('About as simple as it gets, folks')#图的标签
plt.grid(True)#产生网格
plt.savefig("test.png")#保存图像
plt.show()#显示图像
x1 = np.linspace(0.0, 9.9)#画图一
x2 = np.linspace(0.0, 2.6)#画图二
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
plt.subplot(2, 1, 1)#面板设置成2行1列,并取第一个(顺时针编号)
plt.plot(x1, y1, 'yo-')#画图,染色
plt.title('A tale of 3 subplots')
plt.ylabel('Damped oscillation')
plt.subplot(2, 1, 2)#面板设置成2行1列,并取第二个(顺时针编号)
plt.plot(x2, y2, 'r.-')#画图,染色
plt.xlabel('time (s)')
plt.ylabel('Undamped')
plt.show()
7.
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
x_list = [[3,3,2],[4,3,1],[1,2,3],[1,1,2],[2,1,2]]
fig = plt.figure()
ax = fig.gca(projection='3d')
for x in x_list:
ax.scatter(x[0],x[1],x[2],c='r')
plt.show()
from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
X=np.arange(1,10,1)
Y=np.arange(1,10,1)
X, Y = np.meshgrid(X, Y)
Z = 3*X+2*Y+30
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,cmap=cm.jet,linewidth=0, antialiased=True)
ax.set_zlim3d(0,100)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.1)
Y = np.arange(-5, 5, 0.1)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
#画表面,x,y,z坐标, 横向步长,纵向步长,颜色,线宽,是否渐变
ax.set_zlim(-1.01, 1.01)#坐标系的下边界和上边界
ax.zaxis.set_major_locator(LinearLocator(10))#设置Z轴标度
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))#Z轴精度
fig.colorbar(surf, shrink=0.5, aspect=5)#shrink颜色条伸缩比例(0-1),aspect颜色条宽度(反比例,数值越大宽度越窄)
plt.show()
8.
import matplotlib.pyplot as plt
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'#设置标签
sizes = [15, 30, 45, 10]#占比,和为100
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']#颜色
explode = (0, 0.1, 0, 0) #展开第二个扇形,即Hogs,间距为0.1
plt.pie(sizes, explode=explode, labels=labels, colors=colors,autopct='%1.1f%%', shadow=True, startangle=90)#startangle控制饼状图的旋转方向
plt.axis('equal')#保证饼状图是正圆,否则会有一点角度偏斜
fig = plt.figure()
ax = fig.gca()
import numpy as np
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,autopct='%1.1f%%', shadow=True, startangle=90, radius=0.25, center=(0, 0), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, radius=0.25, center=(1, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, radius=0.25, center=(0, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90,radius=0.25, center=(1, 0), frame=True)
ax.set_xticks([0, 1])#设置位置
ax.set_yticks([0, 1])
ax.set_xticklabels(["Sunny", "Cloudy"])#设置标签
ax.set_yticklabels(["Dry", "Rainy"])
ax.set_xlim((-0.5, 1.5))
ax.set_ylim((-0.5, 1.5))
ax.set_aspect('equal')
plt.show()
9.
import turtle as t
t.goto(100,0)
for i in range(20):
t.left(80)
t.fd(100)
t.left(135)
t.fd(165)
t.left(125)
t.fd(115)
t.goto(0, 0)
t.clear()
import turtle as t
t.goto(100,0)
for i in range(8):
t.left(80)
t.fd(100)
t.goto(0, 0)
t.clear()
import turtle as t
t.goto(100,0)
for i in range(20):
t.left(80)
t.fd(100)
t.left(135)
t.fd(105)
t.left(125)
t.fd(115)
t.goto(0, 0)
t.clear()
import turtle as t
t.goto(100,0)
for i in range(50):
t.left(80)
t.fd(100)
t.left(135)
t.fd(105)
t.goto(0, 0)
t.clear()
最后我们来个小代码
import Tkinter as *
s = 0
root = Tk()
def main():
#文字
canvas.create_text(200,40,text="点赞数:"+s,fill="blue")
def jia():
s+=1
button=Button(frameLB,text="点赞",width=8,command=jia)
button.grid(row=2, column=1)
#主事件循环
tk.mainloop()
if __name__ == '__main__':
main()