求问python使用matplotlib时遇到的问题
from random import choice
class RandomWalk:
"""一个随机生成漫步数据的类"""
def __init__(self, num_points=5000):
"""初始化要漫步的属性"""
self.num_points = num_points
#所有随机漫步都始于(0,0)
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""计算随机漫步包含的所有点"""
#不断漫步直到列表达到指定的长度
while len(self.x_values) < self.num_points:
#决定前进方向以及沿着这个方向前进的距离
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = ([0, 1, 2, 3, 4])
y_step = y_direction * y_distance
#拒绝原地踏步
if x_step == 0 and y_step == 0:
continue
#计算下一个点的x和y值
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
self.x_values.append(x)
self.y_value.append(y)
调用上图代码
import matplotlib.pyplot as plt
from aaaaaa import RandomWalk
rw = RandomWalk()
rw.fill_walk()
plt.style.use('classic')
fig, ax = plt.subplots()
ax.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
运行出现Traceback (most recent call last):
File "C:\Users\86199\Desktop\rw_visual.py", line 6, in <module>
rw.fill_walk()
File "C:\Users\86199\Desktop\aaaaaa.py", line 37, in fill_walk
y = self.y_values[-1] + y_step
TypeError: unsupported operand type(s) for +: 'int' and 'list'