首先,下载pygal。
我是用pycharm直接就可以下载,懒人必备。
也可以在DOS窗口
python -m pip install --user pygal
安装好之后可以输入下列命令行,出现下图就是安装正确。
下面看看代码
是一个6面骰子和10面骰子,投掷5000次的直方图。
from random import randint
import pygal
class Die():
'''表示一个骰子的类'''
def __init__(self, num_sides=6):
self.num_sides = num_sides
def roll(self):
'''返回一个位于1和骰子面数之间的数'''
return randint(1, self.num_sides)
die1 =Die(6)
die2 = Die(num_sides=10)
#掷几次骰子,并保存至列表中
results = []
for roll_num in range(5000):
result = die1.roll() + die2.roll()
results.append(result)
print(len(results))
#分析结果
frequencies = []
max_result = die1.num_sides + die2.num_sides
for values in range(2, max_result+1):
frequency = results.count(values)
frequencies.append(frequency)
print(frequencies)
hist = pygal.Bar()
hist.title = 'Results of rolling one D6 1000times'
hist.x_labels = range(2, max_result+1)
hist.y_labels = range(0, 5001, 500)
hist.y_title = 'Frequency of Result'
hist.x_title = 'Frequency if Result'
hist.add('D6+D10', frequencies)
hist.render_to_file('die_visual.svg')
这是数据直方图
使用matplotlib 可视化进行模拟投掷骰子的情况。
import matplotlib.pyplot as plt
from random import randint
class Die():
def __init__(self, num_points=6):
self.num_points = num_points
def roll(self):
return randint(1, self.num_points)
die = Die()
results = []
'''将掷骰子的结果保存在列表中'''
for roll_num in range(1000000):
result = die.roll()
results.append(result)
print(len(results))
frequencies = []
'''将点数出现的频率保存在列表中'''
for frequency in range(1, die.num_points+1):
value = results.count(frequency)
frequencies.append(value)
print(frequencies)
x_values = list(x for x in range(1, die.num_points+1))
y_values = frequencies
plt.plot(x_values, y_values, linewidth=5)
plt.title('D6')
plt.xlabel('x', fontsize=14)
plt.ylabel('y', fontsize=14)
plt.show()
通过pygal可视化模拟随机漫步的情况
from random import choice
import pygal
class RandomWalk():
def __init__(self, num_points=5000):
self.num_points = num_points
'''使起点为0'''
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
while len(self.x_values) < self.num_points:
'''控制方向和距离'''
x_directions = choice([1, -1])
x_distance = choice(list(i for i in range(0, 7)))
x_step = x_directions * x_distance
y_directions = choice([1, -1])
y_distance = choice(list(j for j in range(0, 7)))
y_step = y_directions * 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)
rw = RandomWalk()
rw.fill_walk()
hist = pygal.XY(stroke=False)
hist.title = 'Random walk'
hist.add('D6', [(rw.x_values[i], rw.y_values[i]) for i in range(0, rw.num_points)])
hist.render_to_file('D6_die.svg')