本章知识小结:
1、使用matplotlib创建简单的图表
2、使用plotly绘制直方图探索掷多个骰子结果
1、安装Matplotlib 1 python3 -m pip install --user matplotlib
2、绘制简单的折线图 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 import matplotlib.pyplot as pltinput_values = [1 , 2 , 3 , 4 , 5 ] squares = [1 , 4 , 9 , 16 , 25 ] plt.style.use('seaborn' ) fig, ax = plt.subplots() ax.plot(input_values, squares, linewidth=3 ) ax.set_title("Square Numbers" , fontsize=24 ) ax.set_xlabel("Value" , fontsize=14 ) ax.set_ylabel("Square of Value" , fontsize=14 ) ax.tick_params(axis='both' , labelsize=14 ) plt.show()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 import matplotlib.pyplot as pltx_values = range (1 , 1001 ) y_values = [x**2 for x in x_values] plt.style.use('seaborn' ) fig, ax = plt.subplots() ax.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, s=10 ) ax.set_title("Square Numbers" , fontsize=24 ) ax.set_xlabel("Value" , fontsize=14 ) ax.set_ylabel("Square of Value" , fontsize=14 ) ax.tick_params(axis='both' , which='major' , labelsize=14 ) ax.axis([0 , 1100 , 0 , 1100000 ]) plt.show()
1 2 plt.savefig('myplot.png' , bbox_inches='tight' )
3、随机漫步 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 from random import choiceclass RandomWalk : """A class to generate random walks.""" def __init__ (self, num_points=5000 ): self .num_points = num_points self .x_values = [0 ] self .y_values = [0 ] def fill_walk (self ): while len (self .x_values) < self .num_points: x_direction = choice([1 , -1 ]) x_distance = choice([0 , 1 , 2 , 3 , 4 ]) x_step = x_direction * x_distance y_direction = choice([1 , -1 ]) y_distance = choice([0 , 1 , 2 , 3 , 4 ]) y_step = y_direction * y_distance if x_step == 0 and y_step == 0 : continue x = self .x_values[-1 ] + x_step y = self .y_values[-1 ] + y_step self .x_values.append(x) self .y_values.append(y)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 import matplotlib.pyplot as pltfrom random_walk import RandomWalkwhile True : rw = RandomWalk(50_000 ) rw.fill_walk() plt.style.use('classic' ) fig, ax = plt.subplots(figsize=(15 , 9 )) point_numbers = range (rw.num_points) ax.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolors='none' , s=1 ) ax.scatter(0 , 0 , c='green' , edgecolors='none' , s=100 ) ax.scatter(rw.x_values[-1 ], rw.y_values[-1 ], c='red' , edgecolors='none' , s=100 ) ax.get_xaxis().set_visible(False ) ax.get_yaxis().set_visible(False ) plt.show() keep_running = input ("Make another walk? (y/n): " ) if keep_running == 'n' : break
4、使用Plotly模拟掷骰子 使用Plotly包来生成交互式图标(它生成的图表会自动缩放以适合观看者的屏幕,亦可交互式向用户展示特定元素)
1 python -m pip install --user plotly
4.1 die.py 模拟一个筛子的情况,生成示例调用roll会随机生成1~6
1 2 3 4 5 6 7 8 9 10 11 12 13 14 from random import randintclass Die : def __init__ (self, num_sides=6 ): self .num_sides = num_sides def roll (self ): return randint(1 , self .num_sides)
4.2 掷骰子、分析结果、绘制直方图 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 from plotly.graph_objs import Bar, Layoutfrom plotly import offlinefrom die import Diedie = Die() results = [] for roll_num in range (1000 ): result = die.roll() results.append(result) frequencies = [] for value in range (1 , die.num_sides+1 ): frequency = results.count(value) frequencies.append(frequency) x_values = list (range (1 , die.num_sides+1 )) data = [Bar(x=x_values, y=frequencies)] x_axis_config = {'title' : 'Result' } y_axis_config = {'title' : 'Frequency of Result' } my_layout = Layout(title='Results of rolling one D6 1000 times' , xaxis=x_axis_config, yaxis=y_axis_config) offline.plot({'data' : data, 'layout' : my_layout}, filename='d6.html' )
4.3 投掷两枚六面骰子的结果 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 from plotly.graph_objs import Bar, Layoutfrom plotly import offlinefrom die import Diedie_1 = Die() die_2 = Die() results = [] for roll_num in range (1000 ): result = die_1.roll() + die_2.roll() results.append(result) 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) x_values = list (range (2 , max_result+1 )) data = [Bar(x=x_values, y=frequencies)] x_axis_config = {'title' : 'Result' , 'dtick' : 1 } y_axis_config = {'title' : 'Frequency of Result' } my_layout = Layout(title='Results of rolling two D6 dice 1000 times' , xaxis=x_axis_config, yaxis=y_axis_config) offline.plot({'data' : data, 'layout' : my_layout}, filename='d6_d6.html' )
4.4 一枚六面、一枚十骰子结果 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 from plotly.graph_objs import Bar, Layoutfrom plotly import offlinefrom die import Diedie_1 = Die() die_2 = Die(10 ) results = [] for roll_num in range (50_000 ): result = die_1.roll() + die_2.roll() results.append(result) 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) x_values = list (range (2 , max_result+1 )) data = [Bar(x=x_values, y=frequencies)] x_axis_config = {'title' : 'Result' , 'dtick' : 1 } y_axis_config = {'title' : 'Frequency of Result' } my_layout = Layout(title='Results of rolling a D6 and a D10 50000 times' , xaxis=x_axis_config, yaxis=y_axis_config) offline.plot({'data' : data, 'layout' : my_layout}, filename='d6_d10.html' )