《python程式設計從入門到實踐》15-10練習
阿新 • • 發佈:2018-12-25
練習使用本章介紹的兩個庫:嘗試使用matplotlib通過視覺化來模擬擲骰子的情況,並嘗試使用Pygal通過視覺化來模擬隨機漫步的情況
下面僅列出相關程式,匯入的類為書中所寫的類
from die import Die import matplotlib.pyplot as plt import matplotlib.patches as mpatches die_1 = Die() die_2 = Die(10) results = [] for roll_num in range(50000): #result = die_1.roll() result = die_1.roll() + die_2.roll() results.append(result) frequencies =[] #max_results = die_1.num_sides max_results = die_1.num_sides + die_2.num_sides X_Range = list(set(results)) for value in X_Range: frequency = results.count(value) frequencies.append(frequency) plt.bar(X_Range,frequencies,color = 'Pink',align='center',label = 'D6+D6') plt.xticks(X_Range) plt.xlabel("Results",fontsize = 8) plt.ylabel("Frequencies", fontsize = 8) #圖例 pink_patch = mpatches.Patch(color='Pink', label='D6+D6') plt.legend(handles=[pink_patch]) plt.show()
輸出如圖所示
用Pygal實現隨機漫步的程式為:
結果如圖import pygal from random_walk import RandomWalk rw = RandomWalk(1000) rw.fill_walk() xy_chart = pygal.XY(stroke = False) #stroke=False散點不連線 xy_chart.title = 'RandomWalk' pygal.Line(include_x_axis = False,include_y_axis = False) #把生成的值變成座標 xy_list = [] for (x,y) in zip(rw.x_values,rw.y_values): xy_list.append((x,y)) xy_chart.add('data', xy_list) xy_chart.render_to_file('RandomWalk.svg')
相信解法多種多樣,看完了基礎的就直接學後面的了,其中pygal想換顏色和隱藏座標軸還沒實現,如有大神知道,希望能告知~拜謝!