如题,示例代码如下:
import matplotlib.pyplot as plt
import numpy as np
import random
# import time
plt.ion()
fig = plt.figure(figsize=(10, 6))
ax = fig.add_subplot(1, 1, 1, aspect='equal') # aspect表示坐标轴刻度一致
r1 = random.randint(5, 15)
r2 = random.randint(5, 15)
v1 = random.randint(2, 10) # 角速度,表示1秒钟增加3度
v2 = random.randint(2, 10)
axis_length = max(r1, r2) + 2
ax.axis([-axis_length, axis_length, -axis_length, axis_length])
# ax.set_xticks([])
ax.axis('off') # 坐标轴不显示
# 画两个同心圆
def draw_two_circle():
xx1 = r1 * np.cos(np.linspace(0, 2 * np.pi, 50))
yy1 = r1 * np.sin(np.linspace(0, 2 * np.pi, 50))
ax.plot(xx1, yy1)
xx2 = r2 * np.cos(np.linspace(0, 2 * np.pi, 50))
yy2 = r2 * np.sin(np.linspace(0, 2 * np.pi, 50))
ax.plot(xx2, yy2)
def draw_two_dot():
for t in range(0, 100, 1):
theta1 = v1 * t
theta2 = v2 * t
# print(theta)
x1 = r1 * np.cos(theta1 * np.pi / 180)
y1 = r1 * np.sin(theta1 * np.pi / 180)
x2 = r2 * np.cos(theta2 * np.pi / 180)
y2 = r2 * np.sin(theta2 * np.pi / 180)
line1 = ax.plot(x1, y1, 'ro', markersize=10)
line2 = ax.plot(x2, y2, 'm*', markersize=15)
plt.pause(0.1)
ax.lines.remove(line1[0]) # 用此种方法实现擦除模式,类似于matlab 的hold off
ax.lines.remove(line2[0])
def draw_two_dot_with_line():
for t in range(0, 100, 1):
theta1 = v1 * t
theta2 = v2 * t
# print(theta)
x1 = r1 * np.cos(theta1 * np.pi / 180)
y1 = r1 * np.sin(theta1 * np.pi / 180)
x2 = r2 * np.cos(theta2 * np.pi / 180)
y2 = r2 * np.sin(theta2 * np.pi / 180)
line1 = ax.plot(x1, y1, 'ro', markersize=10)
line2 = ax.plot(x2, y2, 'm*', markersize=15)
ax.plot([x1, x2], [y1, y2], color=(0, 0, 0, 1))
plt.pause(0.1)
ax.lines.remove(line1[0]) # 用此种方法实现擦除模式,类似于matlab 的hold off
ax.lines.remove(line2[0])
def draw_line():
for t in range(0, 600, 1):
theta1 = v1 * t
theta2 = v2 * t
# print(theta)
x1 = r1 * np.cos(theta1 * np.pi / 180)
y1 = r1 * np.sin(theta1 * np.pi / 180)
x2 = r2 * np.cos(theta2 * np.pi / 180)
y2 = r2 * np.sin(theta2 * np.pi / 180)
# time.sleep(0.5)
# ax.scatter(x, y)
# plt.draw()
line = ax.plot([x1, x2], [y1, y2], color=(0, 0, 0, 1)) # 不用设置color='rgba(0, 0, 0, 0.1)'
plt.pause(0.01)
# ax.lines.remove(line[0]) # 用此种方法实现擦除模式,类似于matlab 的hold off
if __name__ == '__main__':
draw_two_circle()
draw_two_dot()
# draw_two_dot_with_line()
# draw_line()
相关知识点:
1.设置曲线的rgba颜色
示例中的代码为line = ax.plot([x1, x2], [y1, y2], color=(0, 0, 0, 1))
,直接设置color=(0, 0, 0, 1),而不是color='rgba(0, 0, 0, 1)'。并且,color=(0, 0, 0, 1)的数值范围均为0和1之间,若有普通rbga(100, 200, 30, 0.5)的颜色,则可设置为color=(100/255, 200/255, 30/255, 0.5)。
2.设置坐标轴刻度长度一致
示例中的代码为ax = fig.add_subplot(1, 1, 1, aspect='equal')
,aspect='equal'表示坐标轴刻度长度一致。
3.隐藏坐标轴
示例中的代码为ax.axis('off')
。
4.实现擦除模式
Matplotlib没有类似于Matlab中的hold on和hold off设置,需要手动实现,实现方式也简单,示例中的代码为:
line1 = ax.plot(x1, y1, 'ro', markersize=10)
line2 = ax.plot(x2, y2, 'm*', markersize=15)
ax.plot([x1, x2], [y1, y2], color=(0, 0, 0, 1))
plt.pause(0.1)
ax.lines.remove(line1[0]) # 用此种方法实现擦除模式,类似于matlab 的hold off
ax.lines.remove(line2[0])
原理就是ax实际上是一个列表,里面存储了许多画出来的线条句柄,删除相应线条句柄即可。