数据可视化用来将下载的数据通过可视化表示,常规的形式是生成一张美观的图片供人们直观参考,得到规律和结论。
主要用到以上两个包,pygal可以生成可以缩放的矢量图片,矢量图片在不同的分辨率下显示时会自动缩放,对于在线浏览是一个不错的选择。
class1.py
from random import choice
class RandomWalk:
def __init__(self, num_points=5000):
self.num_points = num_points
self.x_value = [0]
self.y_value = [0]
def fill_walk(self):
while len(self.x_value) < self.num_points:
x_step = self.get_step()
y_step = self.get_step()
if x_step == 0 and y_step == 0:
continue
next_x = self.x_value[-1] + x_step
next_y = self.y_value[-1] + y_step
self.x_value.append(next_x)
self.y_value.append(next_y)
def get_step(self):
direction = choice([1, -1])
distance = choice([0, 1, 2, 3, 4])
step = direction * distance
return step
main.py
'''主程序'''
import matplotlib.pyplot as plt
from part15.random_walk import RandomWalk
rw = RandomWalk()
rw.get_step()
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_value, rw.y_value, c=point_numbers, cmap=plt.cm.Blues, edgecolors='none',s=15)
plt.show()
class2.py
from random import randint
class Die:
'''这是一个骰子'''
def __init__(self, num_sides=6):
self.num_sides = int(num_sides)
def roll(self):
return randint(1, self.num_sides)
main2.py
import pygal
from part15.die_ import Die
die_1 = Die(6)
die_2 = Die(6)
die_3 = Die(6)
results = []
for roll_time in range(100):
result = die_1.roll() + die_2.roll() + die_3.roll()
results.append(result)
frequencies = []
max_num = die_1.num_sides + die_2.num_sides + die_3.num_sides
for value in range(3, max_num):
frequency = results.count(value)
frequencies.append(frequency)
hist = pygal.Bar()
hist.title = 'Result of rolling one D6 100 times'
hist.x_labels = [x for x in range(3, 18)]
hist._x_title = 'Result'
hist._y_title = 'Frequency of Result'
hist.add('D6', frequencies)
hist.render_to_file('three_dices.svg')