注:文章是用于日常温习做的笔记,不足处欢迎指正。。。
这个章节主要讲怎样去生成某些常用的数据,用到python的包有数学绘图库(matplotlib),可以绘制简单的折线图、散点图等,实践——随机漫步的散点图(折线也可)
Pygal包可以用来生成适合在数字设备显示的图表,实践——掷骰子的直方图结果分析(Pygal的直方图得用.svg保存,发现用谷歌浏览器能看到交互,有些浏览器不支持)
什么都不说上代码吧。。。(脚本里有不少自己加的注释,方便回顾)
掷2个骰子这块,书里是分开同面不同面掷骰子两个简单脚本,这里我合在一个代码并自定义方法实现,个人觉得能简化更容易记住
dice_visual.py
//
"""
掷2枚各自指定面数的骰子
并显示结果
"""
import pygal
from DatePlot.die import Die
def show_image(die_1, die_2, frequencies):
"""将结果以直方图形式展示"""
# 创建直方图实例
hist = pygal.Bar()
# 添加描述
str1 = 'D' + str(die_1.num_sides) + ' + D' + str(die_2.num_sides)
str2 = 'dice_visual' + str(die_1.num_sides) + str(die_2.num_sides) + '.svg'
hist.title = "Result of rolling two dice 100 times."
hist.x_title = "Result"
hist.y_title = "Frequency of result"
hist.x_labels = get_xlabels(die_1, die_2)
hist.add(str1, frequencies)
hist.render_to_file(str2)
def get_xlabels(die_1, die_2):
"""获取x轴的标签列表"""
# 取两枚骰子最大面之和为最大值
result_max = die_1.num_sides + die_2.num_sides
return list(range(2, result_max+1))
def get_results(die_1, die_2, nums):
"""掷骰子多次后将结果存在列表中"""
results = []
for num in range(nums):
result = die_1.roll() + die_2.roll()
results.append(result)
return results
def get_frequencies(die_1, die_2, results):
"""分析骰子结果"""
frequencies = []
x_label = get_xlabels(die_1, die_2)
for value in x_label:
frequencies.append(results.count(value))
return frequencies
def __main__():
"""主函数 """
# 创建2枚不同面数骰子实例 并掷骰子100次后将结果存在列表中
die1 = Die()
die2 = Die(8)
results_d66 = get_results(die1, die1, 100)
results_d68 = get_results(die1, die2, 100)
# 分析结果
frequencies_d66 = get_frequencies(die1, die1, results_d66)
frequencies_d68 = get_frequencies(die1, die2, results_d68)
# 结果可视化
show_image(die1, die1, frequencies_d66)
show_image(die1, die2, frequencies_d68)
__main__()
die.py
//
from random import randint
class Die():
"""表示一个骰子的类"""
def __init__(self, num_sides=6):
"""初始化筛子的属性,默认骰子6面"""
self.num_sides = num_sides
def roll(self):
"""返回一个1到骰子面数之间的随机数"""
return randint(1, self.num_sides)
die.visual.py
//
from DatePlot.die import Die
import pygal
# 创一个骰子实例
die = Die()
# 抛掷几次骰子将结果存在列表中,看是否合理
results = []
for num in range(100):
results.append(die.roll())
# 分析结果计数每个面出现的次数是否合理
frequencies = []
for value in range(1, die.num_sides+1):
frequencies.append(results.count(value))
print(frequencies)
print(sum(frequencies))
# 对比结果可视化,绘制成直方图,图表渲染生成的文件必须以.svg结尾
hist = pygal.Bar()
hist.title = "Results of rolling one D6 100 times"
hist.x_labels = ['1', '2', '3', '4', '5', '6']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D6', frequencies)
hist.render_to_file('die_visual.svg')
mpl_squares.py
//
import matplotlib.pyplot as plt
input_values = [1, 2, 3, 4, 5]
squares = [1, 4, 9, 16, 25]
plt.plot(input_values, squares, linewidth=5)
# 设置图表标题,并给坐标轴加上标签
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Values", fontsize=14)
plt.ylabel("Square of value", fontsize=14)
# 设置刻度的标尺大小
plt.tick_params(axis='both', labelsize=14)
plt.show()
random_walk.py
//
from random import choice
class RandomWalk():
"""一个生成随机漫步数据的类
parameter:
num_points:步数
"""
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.y_values) < self.num_points:
# 决定前进方向和前进的距离
x_step = self.get_step()
y_step = self.get_step()
if x_step == 0 and y_step == 0:
continue
x_value = self.x_values[-1] + x_step
y_value = self.y_values[-1] + y_step
self.x_values.append(x_value)
self.y_values.append(y_value)
@classmethod
def get_step(cls, direct_range=None, distance_range=None):
"""决定前进方向和前进的距离"""
direction = choice([-1, 1])
distance = choice([0, 1, 2, 3, 4])
if direct_range:
direction = choice(direct_range)
if distance_range:
distance = choice(distance_range)
return direction * distance
rw_visual.py
//
import matplotlib.pyplot as plt
from DatePlot.random_walk import RandomWalk
# 只要程序处于活动状态,就不断模拟随机漫步
while True:
# 创建一个随机漫步实例, 并将点绘制出来
rw = RandomWalk(50000)
rw.fill_walk()
# 设置绘图窗口的尺寸,dpi屏幕分辨率 默认80
plt.figure(dpi=128, figsize=(10, 6))
# 按照先后顺序由浅入深
num_points = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=num_points,
cmap=plt.cm.Blues, edgecolors='none', s=1)
# plt.plot(rw.x_values, rw.y_values, c='red', linewidth=1)
# 突出始末点
plt.scatter(0, 0, c='green', edgecolors='none', s=60)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red',
edgecolors='none', s=60)
# 隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
# 互动 是否继续散步
keeping_walk = input("Make another walk? (y/n):")
if keeping_walk == 'n':
break
scatter_squares.py
//
import matplotlib.pyplot as plt
# 简单数值
# x_values = [1, 2, 3, 4, 5]
# y_values = [1, 4, 9, 16, 25]
# 求平方
x_values = list(range(1, 1001))
y_values = [x**2 for x in x_values]
# 求立方
# x_values = list(range(1, 5000))
# y_values = [x**3 for x in x_values]
# edgecolors默认点为蓝色边缘为黑色,cmap 颜色映射,对于c 参照散点值越大颜色越深
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Reds,
edgecolors='none', s=10)
plt.title("Scatter Square", fontsize=24)
plt.xlabel("Values", fontsize=14)
plt.ylabel("Square Value", fontsize=14)
# 这里axis和which均为默认值
plt.tick_params(axis='both', which='major', labelsize=14)
plt.axis([0, 1100, 0, 1100000])
# plt.axis([0, 5100, 0, 127000000000])
# 保存所生成的图片bbox_inches默认值保留表周围多余空白这里去掉
plt.savefig('scatter_square.png', bbox_inches='tight')
# 展示图片
plt.show()
效果图:
1.掷单个骰子,die_visual.svg
2.掷相同骰子,die_visual66.svg
3.掷不相同骰子,die_visual68.svg
1.求平方 , scatter_square.png
2.随机散步
组件方法介绍:
matplotlib地址
pygal地址