Python学习之路(12)生成数据【项目2 数据可视化】
                
            
             
        
            
            数据可视化指的是通过可视化表示来探索数据,它与数据挖掘紧密相关,而数据挖掘指的是使用代码来探索数据集的规律和关联。数据集可以是用一行代码就能表示的小型数字列表,也可以是数以G字节的数据。
1.绘制简单的折线图
下面来使用matplotlib绘制一个简单的折线图,再对其进行定制,以实现信息更丰富的数据可视化。查看使用matplotlib可制作的各种图表,请访问http://matplotlib.org/
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | import matplotlib.pyplot as pltinput_values = [1, 2, 3, 4, 5]
 squares = [1, 4, 9, 16, 25]
 
 plt.plot(input_values, squares, linewidth=5)
 
 plt.title("Square Numbers", fontsize=24)
 plt.xlabel("Value", fontsize=14)
 plt.ylabel("Square of Value", fontsize=14)
 
 plt.tick_params(axis='both', labelsize=14)
 
 plt.show()
 
 
 
 plt.scatter(input_values, squares, s=100, c='red', edgecolor='none')
 plt.show()
 
 | 
1.1自动计算数据
手工计算列表要包含的值可能效率低下,需要绘制的点很多时尤其如此。可以不必手工计算包含点坐标的列表,而让Python循环来替我们完成这种计算。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 
 | import matplotlib.pyplot as pltx_values = list(range(1, 1001))
 
 y_values = [x**2 for x in x_values]
 plt.scatter(x_values, y_values, s=10, c='red', edgecolor='none')
 
 plt.title("Square Numbers", fontsize=24)
 plt.xlabel("Value", fontsize=14)
 plt.ylabel("Square of Value", fontsize=14)
 
 plt.axis([0, 1100, 0, 1100000])
 plt.show()
 
 | 
1.2使用颜色映射
颜色映射 (colormap)是一系列颜色,它们从起始颜色渐变到结束颜色。 在可视化中,颜色映射用于突出数据的规律,例如,你可能用较浅的颜色来显示较小的值,并使用较深的颜色来显示较大的值。
| 12
 3
 4
 5
 6
 7
 8
 
 | import matplotlib.pyplot as pltx_values = list(range(1, 1001))
 y_values = [x**2 for x in x_values]
 
 
 plt.scatter(x_values, y_values, s=10, c=y_values, cmap=plt.cm.Blues, edgecolor='none')
 
 --snip--
 
 | 
1.3自动保存图表
要让程序自动将图表保存到文件中,可将对plt.show() 的调用替换为对 plt.savefig() 的调用。
| 12
 3
 
 | 
 plt.savefig('squares_plot.png', bbox_inches='tight')
 
 | 
2.随机漫步
随机漫步是这样行走得到的路径:每次行走都完全是随机的,没有明确的方向,结果是由一系列随机决策决定的。
| 12
 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
 
 | from random import choiceclass RandomWalk():
 """一个生成随机漫步数据的类"""
 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
 
 next_x = self.x_values[-1] + x_step
 next_y = self.y_values[-1] + y_step
 
 self.x_values.append(next_x)
 
 | 
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | import matplotlib.pyplot as plt
 
 rw = RandomWalk(50000)
 rw.fill_walk()
 point_numbers = list(range(rw.num_points))
 
 
 plt.figure(figsize=(10, 6))
 
 current_axes = plt.axes()
 current_axes.get_xaxis().set_visible(False)
 current_axes.get_yaxis().set_visible(False)
 
 plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolor='none', s=15)
 
 plt.scatter(0, 0, c='green', edgecolors='none', s=100)
 plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)
 plt.show()
 
 | 
3.使用Pygal模拟掷骰子
使用Python可视化包Pygal来生成可缩放的矢量图形文件。对于需要在尺寸不同的屏幕上显示的图表,这很有用,因为它们将自动缩放,以适合观看者的屏幕。如果你打算以在线方式使用图表,请考虑使用Pygal来生成它们,这样它们在任何设备上显示时都会很美观。
要了解使用Pygal可创建什么样的图表,请查看图表类型画廊:访问 http://www.pygal.org/ ,单击Documentation,再单击Chart types。
3.1掷骰子
下面的类模拟掷一个骰子:
| 12
 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
 
 | from random import randintclass Die():
 """表示一个骰子的类"""
 def __init__(self, num_sides=6):
 """骰子默认为6面"""
 self.num_sides = num_sides
 def roll(self):
 """返回一个位于1和骰子面数之间的随机值"""
 return randint(1, self.num_sides)
 
 die = Die()
 
 results = []
 for roll_num in range(1000):
 result = die.roll()
 results.append(result)
 print(results)
 
 frequencies = []
 for value in range(1, die.num_sides+1):
 frequency = results.count(value)
 frequencies.append(frequency)
 print(frequencies)
 
 import pygal
 
 hist = pygal.Bar()
 hist.title = "Result 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')
 
 | 
掷两个骰子:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 
 | import pygal
 die_1 = Die()
 die_2 = Die(10)
 
 results = []
 for roll_num in range(50000):
 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)
 
 hist = pygal.Bar()
 hist.title = "Result of rolling two D6 dice 1000 times."
 hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16']
 hist.x_title = "Result"
 hist.y_title = "Frequency of Result"
 hist.add('D6 + D10', frequencies)
 hist.render_to_file('die_visual.svg')
 
 |