数据可视化
安装matplotlib包
由于我的是windows系统,分享一下windows系统下matplotlib的安装
- win+R–>输入cmd,输入python -m pip install -U pip setuptools进行升级
- 升级完毕后输入python -m pip install matplotlib自动下载以及安装
- 在python idle中或者打开pycharm 中左下角的python console输入import matplotlib,无问题即安装成功
简单折线图的绘制
import matplotlib.pyplot as plt
squares = [1,4,9,16,25]
plt.plot(squares)
plt.show()
- 首先导入matplotlib库中的pyplot模块,这个模块中有许多生成图标的函数,制定为别名更加方便输入
- 创建列表,传递给plot()函数,自动绘制图形,show()函数展示绘制的图形
修改标签文字和线条粗细
import matplotlib.pyplot as plt
values = [1,2,3,4,5] # x轴坐标
squares = [1,4,9,16,25] # y轴坐标
plt.plot(values,squares,linewidth = 15) # 设置线条宽度
plt.title('squares numbers',fontsize = 24) # (图表标题,字号)
plt.xlabel('value',fontsize = 14) # (x轴名称,字号)
plt.ylabel('squares of value',fontsize = 14)
plt.tick_params(axis = 'both',labelsize = 14) # 设置刻度样式,x,y代表设置x,y轴,both代表两个均设置,labelsize为字号
plt.show()
scatter绘制散点图及设置样式
在散点图中可以根据你的意愿对图中某些点的样式进行设置,可以设置其颜色等,对于众多数据,也可以使一部分设置一个样式,另一部分显示另个一样式
import matplotlib.pyplot as plt
plt.scatter(2,4,s=10) # s设置点的尺寸
plt.title('scatter square number',fontsize=24)
plt.xlabel('value',fontsize = 14)
plt.ylabel('square of value',fontsize = 14)
plt.tick_params(axis='both',which = 'major',labelsize = 14)
# which表示主副刻度线,major表示主刻度线,minor表示副刻度线,both表示同时设置
plt.show()
自动计算数据
对于有大量数据的情况,单个输入就显得十分低效,因此可以使用循环来操作
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 = 'red',edgecolors = 'none,s=10)
--snip-- # 设置坐标轴以及标题
plt.axis([0,1100,0,1100000]) # 设置坐标轴范围,前面为x轴,后面为y轴
plt.show()
c设置点的颜色,默认蓝色,可以直接使用红色黄色等字符串表明,也可以使用RGB指明,如
c = [0.3,0.2,1],edgecolors为点的边框颜色,默认黑色
颜色映射
--snip--
plt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Blues,edgecolors='none',s=40)
--snip--
设置颜色映射必须先设置参数c,表示颜色的变化范围,上述代码将其变为一个y值列表,再告诉cmap用哪个映射
cmap.cm.Blues表示颜色映射,Blues表示蓝色渐变,可以在matplotlib.org网站–Examples–Color–Colormap reference找到众多渐变的名称,代替前面说的Blues即可
课后习题
15-1立方(彩色立方)
import matplotlib.pyplot as plt
# 显示前五个数的立方
x_values = [1,2,3,4,5]
y_values = [1,8,27,64,125]
plt.scatter(x_values,y_values,c = 'red',edgecolors='none',s=40)
plt.title('cube number',fontsize = 24)
plt.xlabel('values',fontsize = 14)
plt.ylabel('cube value',fontsize = 14)
plt.tick_params(axis='both',labelsize = 14)
plt.show()
import matplotlib.pyplot as plt
#显示前5000个数的立方
x__values = list(range(5001))
y__values = [x**3 for x in x__values]
plt.scatter(x__values,y__values,c = y__values,cmap=plt.cm.viridis,edgecolors='none',s=10)
plt.title('cube number',fontsize = 24)
plt.xlabel('values',fontsize = 14)
plt.ylabel('cube value',fontsize = 14)
plt.tick_params(axis='both',labelsize = 14)
plt.show()
随机漫步
生成随机漫步数据,每次的行走都是随机的,最终形成随机路径
创建Randomwalk()类
from random import choice
class Randomwalk():
"""命名为random_walk文件"""
def __init__(self, num_point=5000):
self.num_point = num_point
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""点的移动"""
while len(self.x_values) < self.num_point:
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)
绘制图
import matplotlib.pyplot as plt
from random_walk import Randomwalk
while True:
rw = Randomwalk() # 创建实例
rw.fill_walk()
point_number = list(range(5000)) # 划定颜色映射的范围
plt.scatter(rw.x_values,rw.y_values,c = point_number,cmap = plt.cm.Blues,s=15)
plt.scatter(0,0,c='red',s=50) #设置首尾点着重显示
plt.scatter(rw.x_values[-1],rw.y_values[-1],c='green',s=50)
plt.axes().get_xaxis().set_visible(False) # 隐藏坐标轴
plt.axes().get_yaxis().set_visible(False)
plt.figure(figsize(10,6)) # 调整画框尺寸
plt.show()
keep_running = input('make another walk?(y/n)')
if keep_running == 'n':
break
课后习题
15-3分子运动
--snip--
plt.plot(rw.x_values,rw.y_values,linewidth=1) # 画轨迹
plt.axes().get_xaxis().set_visible(False) # 隐藏坐标轴
plt.axes().get_yaxis().set_visible(False)
plt.figure(figsize(10,6)) # 调整画框尺寸
plt.show()
keep_running = input('make another walk?(y/n)')
if keep_running == 'n':
break
15-5重构
from random import choice
class Randomwalk():
def __init__(self,num_point = 5000):
self.num_point = num_point
self.x_values = [0]
self.y_values = [0]
def get_stepx(self):
"""得到x的值"""
x_direction = choice([-2])
x_distance = choice([1, 2, 3, 4, 5, 6, 7, 8])
step_x = x_distance * x_direction
return step_x
def get_stepy(self):
"""得到y的值"""
y_direction = choice([2, -2])
y_distance = choice([0, 1, 2, 3, 4, 5, 6, 7, 8])
step_y = y_distance * y_direction
return step_y
def fill_walk(self):
while len(self.x_values) < self.num_point:
x_step = self.get_stepx()
y_step = self.get_stepy()
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)
pygal模拟投骰子
课后习题
15-6自动生成标签
from die import Die
import pygal
D6 = Die()
D7 = Die(10) # 十面的骰子
result = []
for roll in range(1000):
c = D6.roll() + D7.roll()
result.append(c)
frequency = []
max = D6.side + D7.side
for value in range(2,max+1):
fre = result.count(value)
frequency.append(fre)
print(frequency)
hist = pygal.Bar()
hist.title = 'results'
hist.x_labels = [x for x in range(2,max+1)] # 循环
hist.x_title = 'result'
hist.y_title = 'frequency of result'
hist.add('D6+D7',frequency)
hist.render_to_file('die.svg')
15-7两个D8骰子
--snip--
D6 = Die(8)
D7 = Die(8)
--snip--
15-8掷三个骰子
--snip--
D6 = Die()
D7 = Die()
D8 = Die()
--snip--
for roll in range(1000):
c = D6.roll() + D7.roll() + D8.roll()
--snip--
max = D6.side + D7.side + D8.side
for value in range(3,max+1):
--snip--
hist.x_labels = [x for x in range(3,max+1)]
--snip--
15-9点数相乘
from die import Die
import pygal
D6 = Die()
D7 = Die()
# D8 = Die()
result = []
for roll in range(1000):
c = D6.roll() * D7.roll()
result.append(c)
frequency = []
max = D6.side * D7.side
for value in range(1,max+1):
fre = result.count(value)
frequency.append(fre)
print(frequency)
hist = pygal.Bar()
hist.title = 'results'
hist.x_labels = [x for x in range(1,max+1)]
hist.x_title = 'result'
hist.y_title = 'frequency of result'
hist.add('D6+D7',frequency)
hist.render_to_file('die.svg')