Chapter15-生成数据(项目2:数据可视化)

range() 函数可创建一个整数列表,如:range(10)     # 从 0 开始到 10    得到 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

#15-1 立方 :数字的三次方被称为其立方。请绘制一个图形,显示前5个整数的立方值,
# 再绘制一个图形,显示前5000个整数的立方值。
#####################图一########################
import matplotlib.pyplot as plt
x_values = [1,2,3,4,5]
y_values = [x**3 for x in x_values]
plt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Blues,edgecolors='none',s=40)
plt.show()

#####################图二########################
import matplotlib.pyplot as plt
x_values = list(range(1,5001))
y_values = [x**3 for x in x_values]
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.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Blues,edgecolors='none',s=40)
plt.show()

结果:                  (图一)                                                                               (图二)

                 

#15-2 彩色立方 :给你前面绘制的立方图指定颜色映射。
import matplotlib.pyplot as plt
x_values = list(range(1,5001))
y_values = [x**3 for x in x_values]
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.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Set3,edgecolors='none',s=40)
plt.show()
plt.savefig('colorful_line.png',bbox_inches='tight')

15-2结果:

# 15-3 分子运动 :修改rw_visual.py,将其中的plt.scatter() 替换为plt.plot() 。为模拟花粉在水滴表面的运动路径,
# 向plt.plot() 传递rw.x_values 和rw.y_values ,并指定实参值linewidth 。使用5000个点而不是50000个点。
#########################rw_visual.py##############################
import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
	rw = RandomWalk()
	rw.fill_walk()
	point_numbers = list(range(rw.num_points))
	plt.figure(dpi=128,figsize=(10,6))
	plt.plot(rw.x_values,rw.y_values,linewidth=2)
	plt.scatter(0,0,c='green',s=100)
	plt.scatter(rw.x_values[-1],rw.y_values[-1], c='red', 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
#######################random_work.py################################
from random import choice
class RandomWalk():
	"""生成随机漫步数据的类"""
	def __init__(self,num_points=5000):
		self.num_points = num_points
		# 所有随机漫步都始于(0, 0)
		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)

15-3结果:

#15-4 改进的随机漫步 :在类RandomWalk 中,x_step 和y_step 是根据相同的条件生成的:从列表[1, -1] 中随机地选择方向,并从列表[0, 1, 2, 3, 4]
#中随机地选择距离。请修改这些列表中的值,看看对随机漫步路径有何影响。尝试使用更长的距离选择列表,如0~8;或者将-1从 x 或 y 方向列表中删除。
################################rw_visual.py##########################################
import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
	rw = RandomWalk()
	rw.fill_walk()
	point_numbers = list(range(rw.num_points))
	plt.figure(figsize=(10,6))
	plt.plot(rw.x_values,rw.y_values,linewidth=2)
	plt.scatter(0,0,c='green',s=100)
	plt.scatter(rw.x_values[-1],rw.y_values[-1], c='red', 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
#############################random_walk.py#############################################
from random import choice
class RandomWalk():
	"""生成随机漫步数据的类"""
	def __init__(self,num_points=5000):
		self.num_points = num_points
		# 所有随机漫步都始于(0, 0)
		self.x_values = [0]
		self.y_values = [0]
	def fill_walk(self):
		# 不断漫步,直到列表达到指定的长度
		while len(self.x_values) < self.num_points:
			# 决定前进方向以及沿这个方向前进的距离
			x_direction = choice([1])
			x_distance = choice(list(range(8)))
			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)

15-4结果:

#15-5 重构:方法fill_walk()很长。请新建一个名为get_step() 的方法,用于确定每次漫步的距离和方向,并计算这次漫步将如何移动。然后,
# 在fill_walk() 中调用get_step() 两次:
################################rw_visual.py##########################################
import matplotlib.pyplot as plt
from random_walk import RandomWalk
while True:
	rw = RandomWalk()
	rw.fill_walk()
	point_numbers = list(range(rw.num_points))
	plt.figure(figsize=(10,6))
	plt.plot(rw.x_values,rw.y_values,linewidth=2)
	plt.scatter(0,0,c='green',s=100)
	plt.scatter(rw.x_values[-1],rw.y_values[-1], c='red', 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
################################random_walk.py########################################
from random import choice
class RandomWalk():
	"""生成随机漫步数据的类"""
	def __init__(self,num_points=5000):
		self.num_points = num_points
		# 所有随机漫步都始于(0, 0)
		self.x_values = [0]
		self.y_values = [0]
	def get_step(self):
		direction = choice([-1, 1])
		distance = choice([0, 1, 2, 3, 4])
		return direction * distance
	def fill_walk(self):
		# 不断漫步,直到列表达到指定的长度
		while len(self.x_values) < self.num_points:
			x_step = self.get_step()
			y_step = self.get_step()
			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)

15-5结果:

#15-6 自动生成标签 :请修改die.py和dice_visual.py,将用来设置hist.x_labels 值的列表替换为一个自动生成这种列表的循环。
# 如果你熟悉列表解析,可尝试将die_visual.py和dice_visual.py中的其他for 循环也替换为列表解析。
####################################die_visual.py#####################################
import pygal
from die import Die
die = Die()
def num2char(num):
	return str(num)
results = []
for roll_num in range(100):
	result = die.roll()
	results.append(result)
print(results)

frequencies = []
max_num = die.num_sides+1
for value in range(1,max_num):
	frequency = results.count(value)
	frequencies.append(frequency)
print(frequencies)

hist = pygal.Bar()
hist.title = "Results of rolling one D6 1000 times"
hist.x_labels = list(map(num2char,list(range(1,max_num))))
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D6',frequencies)
hist.render_to_file('die_visual.svg')
#####################################die.py####################################
from random import randint
class Die():
	def __init__(self,num_sides=6):
		self.num_sides = num_sides
	def roll(self):
		return randint(1,self.num_sides)

15-6结果:
[2, 1, 4, 6, 2, 2, 2, 4, 4, 1, 6, 3, 5, 5, 4, 1, 4, 5, 4, 4, 2, 2, 4, 1, 3, 4, 2, 2, 6, 2, 5, 4, 5, 5, 5, 4, 6, 1, 4, 3, 4, 6, 4, 3, 4, 3, 3, 5, 4, 5, 2, 4, 4, 4, 5, 2, 3, 3, 5, 6, 4, 3, 4, 5, 2, 5, 6, 1, 3, 5, 4, 2, 2, 3, 3, 2, 3, 4, 3, 3, 4, 4, 1, 6, 6, 6, 1, 4, 4, 6, 4, 5, 4, 1, 3, 6, 5, 3, 6, 4]
[9, 15, 17, 30, 16, 13]

15-6结果: 

# 15-7 两个D8骰子: 请模拟同时掷两个8面骰子1000次的结果。逐渐增加掷骰子的次数,直到系统不堪重负为止。
##dice_visual.py##
import pygal
from die import Die
die_1 = Die(8)
die_2 = Die(8)
def num2char(num):
	return str(num)
results = []
for roll_num in range(1000):
	result = die_1.roll() + die_2.roll()
	results.append(result)
print(results)

frequencies = []
max_num = die_1.num_sides+die_2.num_sides+1
for value in range(2,max_num):
	frequency = results.count(value)
	frequencies.append(frequency)
print(frequencies)

hist = pygal.Bar()
hist.title = "Results of rolling one D8 1000 times"
hist.x_labels = list(map(num2char,list(range(2,max_num))))
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D8 + D8',frequencies)
hist.render_to_file('dice_visual.svg')
##die.py##
from random import randint
class Die():
	def __init__(self,num_sides=6):
		self.num_sides = num_sides
	def roll(self):
		return randint(1,self.num_sides)

#15-7结果:

# 15-8 同时掷三个骰子 :如果你同时掷三个D6骰子,可能得到的最小点数为3,而最大点数为18。请通过可视化展示同时掷三个D6骰子的结果。
###three_visal.py####
import pygal
from die import Die
die_1 = Die(6)
die_2 = Die(6)
die_3 = Die(6)
def num2char(num):
	return str(num)
results = []
for roll_num in range(1000):
	result = die_1.roll() + die_2.roll() + die_3.roll()
	results.append(result)
print(results)

frequencies = []
max_num = die_1.num_sides+die_2.num_sides+die_3.num_sides+1
for value in range(3,max_num):
	frequency = results.count(value)
	frequencies.append(frequency)
print(frequencies)

hist = pygal.Bar()
hist.title = "Results of rolling three D6 1000 times"
hist.x_labels = list(map(num2char,list(range(3,max_num))))
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D6 + D6 +D6',frequencies)
hist.render_to_file('three_visual.svg')
###die.py###
from random import randint
class Die():
	def __init__(self,num_sides=6):
		self.num_sides = num_sides
	def roll(self):
		return randint(1,self.num_sides)

15-8结果:

# 15-9 将点数相乘 :同时掷两个骰子时,通常将它们的点数相加。请通过可视化展示将两个骰子的点数相乘的结果。
###dice_visual.py###
import pygal
from die import Die
die_1 = Die(6)
die_2 = Die(6)
def num2char(num):
	return str(num)
results = []
for roll_num in range(1000):
	result = die_1.roll() * die_2.roll()
	results.append(result)
print(results)

hist = pygal.Bar()
hist.title = "Results of rolling two D6 1000 times"
frequencies = []
label = []
max_num = die_1.num_sides*die_2.num_sides+1
for value in range(2,max_num):
	frequency = results.count(value)
	if frequency == 0:
		continue
	label.append(num2char(value))
	frequencies.append(frequency)
print(frequencies)
hist.x_labels = label
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D6 + D6',frequencies)
hist.render_to_file('dice_visual.svg')
###die.py###
from random import randint
class Die():
	def __init__(self,num_sides=6):
		self.num_sides = num_sides
	def roll(self):
		return randint(1,self.num_sides)

15-9结果:

 

#15-10 练习使用本章介绍的两个库 :尝试使用matplotlib通过可视化来模拟掷骰子的情况,
# 并尝试使用Pygal通过可视化来模拟随机漫步的情况。
import matplotlib.pyplot as plt
from die import Die
die = Die()
def num2char(num):
	return str(num)
results = []
for roll_num in range(100):
	result = die.roll()
	results.append(result)
print(results)

frequencies = []
max_num = die.num_sides+1
for value in range(1,max_num):
	frequency = results.count(value)
	frequencies.append(frequency)
print(frequencies)

plt.title("Results of rolling one D6 1000 times")
plt.plot(list(range(1,max_num)),frequencies,linewidth = 2)
plt.xlabel("Result",fontsize = 14)
plt.ylabel("Frequency of Result",fontsize = 14)
plt.show()

15-10结果:

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值