1. 绘制简单图
import matplotlib.pyplot as plt
squares=[1,4,9,16,25]
plt.plot(squares)
plt.show()
import matplotlib.pyplot as plt
squares = [1,4,9,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()
#表示为---snip---
#设置图标标题,并给坐标轴加上标签
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)
scatter()绘制散点图
#使用scatter()绘制散点图并设置其样式
import matplotlib.pyplot as plt
#---snip---
plt.scatter(2,4,s=200)
plt.show()
scatter()绘制一系列点
#使用scatter()绘制一系列点
import matplotlib.pyplot as plt
x_value=[1,2,3,4,5]
y_value = [1,4,9,16,25]
plt.scatter(x_value,y_value,s=100)
#---snip---
plt.show()
自动计算数据
#自动计算数据
import matplotlib.pyplot as plt
x_value=list(range(1,1001))
y_value = [x**2 for x in x_value]
plt.scatter(x_value,y_value,s=40)
#plt.scatter(x_value,y_value,edgecolor='none',s=40) #edgecolor='none'删除数据点的轮廓
#plt.scatter(x_value,y_value,c='red',edgecolor='none',s=40) #c='red'/c=(0,0.1,0.7)类似的方法设置数据点的颜色
#---snip---
#设置每个坐标轴的取值范围
plt.axis([0,1100,0,1100000])
plt.show()
颜色映射
#使用颜色映射
import matplotlib.pyplot as plt
x_value=list(range(1,1001))
y_value = [x**2 for x in x_value]
plt.scatter(x_value,y_value,c=y_value,cmap=plt.cm.Blues,edgecolor='none',s=40)
#c=y_value,cmap=plt.cm.Blues类似的方法设置数据点颜色渐变
#---snip---
#设置每个坐标轴的取值范围,x的取值范围[0,1100],y的取值范围[0,1100000]
plt.axis([0,1100,0,1100000])
plt.show()
#plt.savefig('squares_plot.png',bbox_inches='tight') #自动保存图片
plt.savefig('squares_plot.png',bbox_inches='tight')
'''自动保存图片到文件中,第一个实参指定以什么样的文件名保存图表,将存储到xx.py文件所在的同一个目录下,第二个实参指定将图表多余的空白区域裁剪掉'''
2. 随机漫步
RandomWalk()类
#random_walk.py文件
from random import choice
class RandomWalk():
# RandomWalk()类中包括两个方法:_init_()和fill_walk()
'''一个生成随机漫步数据的类'''
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
# 计算下一个点的x和y值
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)
绘制随机漫步图
#rw_visual.py文件
#绘制随机漫步图
import matplotlib.pylab as plt
from random_walk import RandomWalk
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
'''版本二:模拟多次随机漫步'''
import matplotlib.pylab as plt
from random_walk import RandomWalk
# 只要程序处于活动状态,就不断的模拟随机漫步
while True:
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
# 如果输入y,可模拟多次随机漫步,输入n,则结束程序
keep_running = input("Make another walk? (y/n):")
if keep_running == 'n':
break
'''版本三:给随机漫步点着色'''
import matplotlib.pylab as plt
from random_walk import RandomWalk
# 1.只要程序处于活动状态,就不断的模拟随机漫步
while True:
rw = RandomWalk()
rw.fill_walk()
'''使用range()生成一个数字列表,其中包含的数字个数与漫步包含的点数相同,将该列表存储在point_numbers中,以便后面使用它来设置每个漫步点的颜色'''
point_numbers = list(range(rw.num_points))
#2.着色语句
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolors='none', s=15)
#3.绘制起点和终点
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)
#4.隐藏坐标轴
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
随机漫步增加点数
#---snip---表示省略相同部分
#---snip---
while True:
#5.和之前的程序相比,唯一改变的地方,改变了模拟随机漫步的点数
rw = RandomWalk(50000)
rw.fill_walk()
# point_numbers以便后面使用它来设置每个漫步点的颜色
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=50)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=50)
#---snip---
调整尺寸以适合屏幕
#---snip---表示省略相同部分
#---snip---
while True:
rw = RandomWalk()
rw.fill_walk()
# point_numbers以便后面使用它来设置每个漫步点的颜色
point_numbers = list(range(rw.num_points))
#6.设置绘制窗口的尺寸
plt.figure(figsize=(10,6))
#设置屏幕分辨率dpi=128
# plt.figure(dpi=128,figsize=(10,6))
#---snip---
3.使用Pygal模拟掷骰子
创建Die类
#die.py文件
from random import randint
class Die():
'''表示一个骰子'''
def __init__(self, num_sides=6):
self.num_sides = num_sides
def roll(self):
'''返回一个位于1和骰子面数之间的随机数'''
return randint(1, self.num_sides)
测试:掷骰子
#die_visual.py文件
from die import Die
# 创建一个D6
die = Die()
# 掷几次骰子,并将结果存储在一个列表中
results = []
for roll_num in range(100):
result = die.roll()
results.append(result)
print(results)
分析结果
#---snip---表示省略相同部分
#---snip---
for roll_num in range(1000):#模拟次数从100增加到了1000
result = die.roll()
results.append(result)
# 分析结果
frequencies = []
for value in range(1, die.num_sides + 1):
frequency = results.count(value)
frequencies.append(frequency)
print(frequencies)
'''版本2:对结果可视化'''
hist = pygal.Bar()
hist.title = 'Results of rolling two 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')
运行结果
[171, 176, 160, 176, 142, 175]
同时掷两个骰子
import pygal
from die import Die
# 创建两个D6骰子
die_1 = Die()
die_2 = Die()
# 掷几次骰子,并将结果存储在一个列表中
results = []
for roll_num in range(1000):
result = die_1.roll() + die_2.roll()
results.append(result)
# 分析结果(省略,同上列代码相同)
#---snip---
# 对结果进行可视化
hist = pygal.Bar()
hist.title = 'Results of rolling two D6 1000 times.'
hist.x_labels = ['2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
hist.x_title = "Result"
hist.y_title = "Frequency of Result"
hist.add('D6 + D6', frequencies)
hist.render_to_file('dice_visual.svg')
同时掷两个面数不同的骰子
import pygal
from die import Die
# 创建两个D6骰子
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 a D10 50,000 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('dice_visual_2.svg')