直方图绘制,需要引入pygal库。
本程序使用骰子打点的方式,随机出现数据,统计数据出现的个数。
# -*- coding:utf-8 -*-
from random import randint
import pygal
class Die():
"""骰子"""
def __init__(self, num_sides=6):
self.num_sides = num_sides
def roll(self):
return randint(1, self.num_sides)
shaizi = Die() #实例化
#得到样本数据
results = []
for roll_num in range(1000):
results.append(shaizi.roll())
frequencies = []
for value in range(1, shaizi.num_sides+1):
frequency = results.count(value)
frequencies.append(frequency)
print(frequencies)
hist = pygal.Bar()
hist.title = "Results of rolling one D6 1000 times"
hist.x_labels = [x for x in range(1,6)]
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D6', frequencies)
hist.render_to_file('die_visual.svg')
Paste_Image.png
网友评论