Python可視化包Pygal可生成可縮放的矢量圖形文件,可在不一樣尺寸的屏幕上自動縮放,方便觀看。ubuntu
首先安裝pygal,ubuntu終端執行pip install pygal,這裏實測conda install pygal 沒法安裝app
建立一個骰子的類dom
1 from random import randint 2 3 4 class Die(): 5 '''表示一個骰子的類''' 6 7 def __init__(self, num_sides=6): 8 # 骰子默認6面 9 self.num_sides = num_sides 10 11 def roll(self): 12 #返回一個位於1和骰子面數之間的值 13 return randint(1, self.num_sides)
擲1000次骰子,分析各點數出現次數並繪製直方圖ide
import pygal from die import Die #建立一個6面骰子 die = Die() #擲幾回骰子並將結果存儲在列表中 results = [] for roll_num in range(1000): result =die.roll() results.append(result) #print(results) #分析結果:1000次中每一個點數出現的次數 frequencies = [] for value in range(1, die.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 = ['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')#將圖表渲染成svg文件
Figure:svg
擲2個骰子,統計點數之和出現的次數spa
import pygal from die import Die #建立2個6面骰子 die_1 = Die() die_2 = Die() #擲幾回骰子並將結果存儲在列表中 results = [] for roll_num in range(1000): result =die_1.roll() + die_2.roll() results.append(result) #print(results) #分析結果:1000次中每一個點數出現的次數 frequencies = [] max_result = die_1.num_sides + die_2.num_sides for value in range(2, max_result + 1): frequency = results.count(value) frequencies.append(frequency) #print(frequencies) '''建立直方圖,對結果進行可視化''' hist = pygal.Bar()#建立直方圖實例 #屬性設置 hist.title = "Results of rolling two D6 1000 times" hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] #or hist.x_labels = [str(x) for x in range(2, 13)] hist.x_title = "Result" hist.y_title = "Frequency of Result" hist.add('D6 + D6', frequencies)#將標籤及結果添加到圖表中 hist.render_to_file('dice_visual.svg')
Figure:code
同時擲2個面不一樣的骰子50000次,一個6面,一個10面,點數之和相加,觀測 次數blog
1 import pygal 2 from die import Die 3 4 5 #建立1個6面骰子和1個10面骰子 6 die_1 = Die() 7 die_2 = Die(10) 8 #擲幾回骰子並將結果存儲在列表中 9 results = [] 10 for roll_num in range(50000): 11 result =die_1.roll() + die_2.roll() 12 results.append(result) 13 14 #print(results) 15 #分析結果:50000次中每一個點數出現的次數 16 frequencies = [] 17 max_result = die_1.num_sides + die_2.num_sides 18 for value in range(2, max_result + 1): 19 frequency = results.count(value) 20 frequencies.append(frequency) 21 #print(frequencies) 22 '''建立直方圖,對結果進行可視化''' 23 hist = pygal.Bar()#建立直方圖實例 24 #屬性設置 25 hist.title = "Results of rolling a D6 and D10 50000 times" 26 #hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] 27 hist.x_labels = [str(x) for x in range(2, 17)] 28 hist.x_title = "Result" 29 hist.y_title = "Frequency of Result" 30 31 hist.add('D6 + D10', frequencies)#將標籤及結果添加到圖表中 32 hist.render_to_file('different_visual.svg')
Figure:ip