记录自己数据可视化的学习过程(具体内容写在代码注释里)
绘制简单折线图Step 1:修改标签文字和线条粗细Step 2:校正图形
绘制散点图Step 1:绘制一系列的点Step 2:自动计算数据Step 3:使用颜色映射并保存图表
随机漫步Step 1:创建RandomWalk()类Step 2:绘制随机漫步图Step 3:调整图形(如尺寸,颜色等)
使用 Pygal 模拟掷骰子Step 1:创建Die类Step 2:掷骰子Step 3:同时掷两个面数不同的骰子
绘制简单折线图
初始代码如下:
import matplotlib
.pyplot
as plt
squares
= [1, 4, 8, 16, 25]
plt
.plot
(squares
)
plt
.show
()
初始效果图如下: matplotlib是一个数学绘图库,可以用它来制作简单的图表,如折线图和散点图
Step 1:修改标签文字和线条粗细
import matplotlib
.pyplot
as plt
squares
= [1, 4, 8, 16, 25]
plt
.plot
(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
()
Step 2:校正图形
import matplotlib
.pyplot
as plt
input_values
= [1, 2, 3, 4, 5]
squares
= [1, 4, 8, 16, 25]
plt
.plot
(input_values
, squares
, linewidth
=5)
绘制散点图
import matplotlib
.pyplot
as plt
plt
.scatter
(2, 4, s
=200)
plt
.title
("Square Numbers", fontsize
=24)
plt
.xlabel
("Value", fontsize
=14)
plt
.ylabel
("Square of Value", fontsize
=14)
plt
.tick_params
(axis
='both', which
='major', labelsize
=14)
plt
.show
()
Step 1:绘制一系列的点
import matplotlib
.pyplot
as plt
x_values
= [1, 2, 3, 4, 5]
y_values
= [1, 4, 9, 16, 25]
plt
.scatter
(x_values
, y_values
, s
=100)
Step 2:自动计算数据
import matplotlib
.pyplot
as plt
x_values
= list(range(1, 1001))
y_values
= [x
**2 for x
in x_values
]
plt
.scatter
(x_values
, y_values
, s
=40)
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
()
Step 3:使用颜色映射并保存图表
import matplotlib
.pyplot
as plt
x_values
= list(range(1, 1001))
y_values
= [x
**2 for x
in x_values
]
plt
.scatter
(x_values
, y_values
, c
=y_values
, cmap
=plt
.cm
.Blues
, edgecolors
='none', s
=40)
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
.savefig
('squares_plot.png', bbox_inches
='tight')
plt
.show
()
随机漫步
Step 1:创建RandomWalk()类
from random
import choice
class 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
)
self
.y_values
.append
(next_y
)
Step 2:绘制随机漫步图
import matplotlib
.pyplot
as plt
from random_walk
import RandomWalk
rw
= RandomWalk
()
rw
.fill_walk
()
plt
.scatter
(rw
.x_values
, rw
.y_values
, s
=15)
plt
.show
()
Step 3:调整图形(如尺寸,颜色等)
import matplotlib
.pyplot
as plt
from random_walk
import RandomWalk
while True:
rw
= RandomWalk
(50000)
rw
.fill_walk
()
plt
.figure
(figsize
=(10, 6))
point_numbers
= list(range(rw
.num_points
))
plt
.scatter
(rw
.x_values
, rw
.y_values
, c
=point_numbers
, cmap
=plt
.cm
.Blues
,
edgecolors
='none', s
=1)
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
.axes
().get_xaxis
().set_visible
(False)
plt
.axes
().get_yaxis
().set_visible
(False)
plt
.show
()
keep_running
= input("Make another walk? (y/n):")
if keep_running
== 'n':
break
使用 Pygal 模拟掷骰子
Step 1:创建Die类
from random
import randint
class Die():
"""表示一个骰子的类"""
def __init__(self
, num_sides
=6):
"""骰子默认6面"""
self
.num_sides
= num_sides
def roll(self
):
"""返回一个位于1和骰子面数之间的随机值"""
return randint
(1, self
.num_sides
)
Step 2:掷骰子
from die
import Die
import pygal
die
= Die
()
results
= []
for roll_num
in range(1000):
result
= die
.roll
()
results
.append
(result
)
frequencies
= []
for value
in range(1, die
.num_sides
):
frequency
= results
.count
(value
)
frequencies
.append
(frequency
)
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')
Step 3:同时掷两个面数不同的骰子
from die
import Die
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
= "Results of rolling a D6 and D10 50,000 times."
hist
.x_labels
= ['2', '3', '4', '5', '5', '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')