《python编程从入门到实践》15-10练习

练习使用本章介绍的两个库:尝试使用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想换颜色和隐藏坐标轴还没实现,如有大神知道,希望能告知~拜谢!



阅读更多
换一批

没有更多推荐了,返回首页