python编程从入门到实践 之 数据可视化部分总结和回顾(未完待续)
15.1生成数据
matplotlib:是一个数学绘图库,使用它可以制作简单的图标。
pygal包:专注于生成适合在数字设备上显示的图标。通过使用pygal,可以在与图表交互时突出元素以及调整大小,还可以轻松调整整个图表的尺寸。pygal我自己的理解是python graphics adapt library,即python图形适配器。
这两个部分安装就不叙述了,书上有的。安装后在解释器中运行:
import matplotlib如果没有任何出错信息,说明安装正确。
另外,要查看由matplotlib制作的各种图表,请访问:https://matplotlib.org/示例的画廊。单击画廊中的图表,就可以查看用于生成图表的代码。
15.2 绘制简单的折线图
#导入pyplot,并指定了别名plt,避免反复键入pyplot import matplotlib.pyplot as plt # squares = [1,4,9,16,25,36,49] plt.plot(squares) plt.show()注意:我自己实践,可以吧import matplot.pyplot 写成如下形式
from matplotlib import pyplot运行后,得到如下图像
15.2.1修改标签文字和线条粗细
上图中的图标标签太小,线条太细,下面自己定制。
import matplotlib.pyplot as pltsquares = [1,4,9,16,25,36,49] #linewidth决定了plot画的线条的粗细 plt.plot(squares,linewidth=5)#设置图标标题,并加上标签 plt.title("Squares Numbers",fontsize=24) plt.xlabel("Value:",fontsize=14) #加上x轴标签,字体14 plt.ylabel("Square of Value:",fontsize=14) #给y轴加上标签,字体14#设置刻度标记的大小(也就是坐标轴上数字标记的大小) plt.tick_params(axis='both',labelsize=14) plt.show()
15.2.2矫正图形
图形绘制以后,我们发现没有正确地绘制数据:折线图的终点指出6的平方为49,下面来修复这个问题。
当你向plot提供一系列的数字时,它假设第一个数据点对应的x坐标纸为0,但我们的第一个点对应的值x为1,为了改变这种默认的行为,我们可以给plot()同时提供输入值和输出值:
...snip... inputvalues = [1,2,3,4,5,6,7] squares = [1,4,9,16,25,36,49] #linewidth决定了plot画的线条的粗细 plt.plot(inputvalues,squares,linewidth=5) #同时提供输入值和输出值 ...snip...plt还可以指定更多的实际参数。后路将会学习到。
15.2.3
import matplotlib.pyplot as plt#绘制单个点,传给scatter一对x和y坐标即可 plt.scatter(2,4,s=100) plt.show() ~注:scatter可以画单个点,也可以画一系列的点,前者传递单个点的坐标,后者传递2列表。
练习15-1
#15-1(1)import matplotlib.pyplot as plt inputvalues = list(x for x in range(1,6)) values = list(x**3 for x in range(1,6)) plt.scatter(inputvalues,values,s=10) plt.show() ~ #15-1(2) import matplotlib.pyplot as plt inputvalues = list(x for x in range(1,5001)) values = list(x**3 for x in range(1,5001)) #使用颜色渐变模式 plt.scatter(inputvalues,values,c=values,cmap=plt.cm.Blues,s=10) plt.show()知识点总结
一、plt下的plot 和 scatter画图
(仿照mysql语句语法格式,[]内部分是可以省略的部分),有的时候[]代表一个列表,大家可以自己尝试运行代码进行鉴别:
(1)导入库下面的方法
或者
from matplotlib import pyplot as plt(2)画图函数
plt.plot(inputvalues,outputvalues,line_width=NUM)plt.scatter(xvalues,yvalues,s=SQUAREVALUES)表示画散点图,s代表每个点内由多少个像素组成,
这里面有个edgecolor表示有没有轮廓,默认有轮廓,但是我试了下,指定edgecolor='none'后,效果完全一样的。
形如参数c='red',表示指定颜色的参数。对plot和scatter都是适用的。c也可以用rgb颜色模式指定,
例如:c=(0,0,0.2),当值越大,颜色越深,值越小,颜色越淡。
#下面plot函数内的[]不是可省略的意思,是指的一个列表
(3)设置标题,x轴,y轴标签,下面三个函数参数设置方法一致
plt.title("title_contents",fontsize=NUM)
plt.xlabel(...)
plt.ylabel(...)
(4)设置坐标轴刻度大小的函数
plt.tick_params(axis='both',labelsize=NUM)
(5)指定x和y坐标范围(xmaximum和ymuximum分别是x和y坐标的最大值)
plt.axis([0,xmaximum,0,ymaximum])
plt.plot([xvalues_list],y_values,line_width=WIDTH_VALUE),line_width 表示线的宽度是多少像素
(7)显示函数
plt.show() 显示画的图形并且结束程序
plt.savefig('PICTURE_NAME',bbox_inches='tight'),第一个参数表示图像名称,第二个参数表示裁剪多余的部分,tight表示紧身的,代表将裁剪多余的部分
注意:bbox_inches='tight'只是删除图形周围的所有额外空白区域,它在渲染完成后并未实际重新排列图形中的任何内容。
(8)颜色映射
关于颜色映射,类似如下格式
plt.scatter(x_values,y_values,c=y_values,...)
c可以赋值为y_values或者直接赋值一个list(range(len(y_values))),也就是一个自然数列表。如果赋值为自然数列表,那么颜色变化速度慢,如果赋值的列表内的数据变化速度快,那么颜色变化速度非常快。
(9)隐藏坐标轴
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
(10)调整绘图窗口大小,分辨率,背景色等:
plt.figure(figsize(x,y))
例如: plt.figure(figsize=(10,6)),表示绘图窗口是10英寸 * 6英寸
plt.figure(figsize=(10,6),dpi=)
二、pygal生成可缩放的矢量图形文件
如果打算在线方式生成图表,那么pygal很有用,会根据观看者的屏幕来调整图片大小。在任何设备上显示都很美观。
http://www.pygal.org/ 然后进入Documentation,单击Chart types。每个示例都包括源代码,这让你知道这些图表是如何生成的。
pygal知识点:
一、相关知识点
1.定义一个Bar图 hist = pygal.Bar()
2.给图形加标题 hist.title = 'some title'
3.给图形加x坐加标记: hist.x_labels = ['','','','','']是一个列表,列表中的元素可以是str类型,不能是int类型
4.给x,y坐标加标题 hist.x_title = ' ' and hist.y_title = ' '
5.加 标签 + 值 hist.add('label_of_value',y_values) y_values是一个列表
6.渲染到文件 hist.render_to_file('filename') filename必须是一个svg文件
from die import Die import pygaldie = Die() results = [] for roll_num in range(100):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)# 对结果进行可视化 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')再来个2个骰子的程序:
from die import Die import pygaldie1 = Die() die2 = Die()#掷骰子多次,并把结果放在一个列表中 results = [] for roll_num in range(1000):result = die1.roll() + die2.roll()results.append(result)#分析结果 frequencies = [] max_result = die1.num_sides + die2.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 two D6 dice 1000 times.' hist.x_labels = ['2','3','4','5','6','7','8','9','10','11','12'] hist.y_title = 'Frequency of Result'hist.add('D6 + D6',frequencies) hist.render_to_file('two_d6.svg') print(frequencies)15.3随机漫步
练习15-3
#文件walk.py import matplotlib.pyplot as plt from random_walk import RandomWalkwhile True:rw = RandomWalk(5000)rw.fill_walk()plt.figure(figsize=(10,6),dpi=100)num_points = list(range(rw.num_count))#plot 没有edgecolor和像 scatter那样的颜色映射,不能用s设置点的面积,需要用linewidth设置plt.plot(rw.x_values,rw.y_values,c='red',linewidth=1,)plt.scatter(0,0,s=100,c='red',edgecolor='none')plt.scatter(rw.x_values[-1],rw.y_values[-1],s=100,edgecolor='none')#plt.axes().get_xaxis().set_visible(False)#plt.axes().get_yaxis().set_visible(False)plt.show()info = input("Another walk?(y/n)")if info == 'n' or info == 'N':break #文件random_walk.pyfrom random import choice import matplotlib.pyplot as plt class RandomWalk():def __init__(self,num_count = 5000):self.x_values = [0]self.y_values = [0]self.num_count = num_countdef fill_walk(self):while len(self.x_values) < self.num_count: x_direction = choice([1,-1])x_step = choice([0,1,2,3,4])x_step = x_direction * x_stepy_direction = choice([1,-1])y_step = choice([0,1,2,3,4])y_step = y_step * y_directionif x_step == 0 and y_step == 0:continuex_value = x_step + self.x_values[-1]y_value = y_step + self.y_values[-1]self.x_values.append(x_value)self.y_values.append(y_value)练习15-5
random_walk.py改成如下:
from random import choice import matplotlib.pyplot as plt class RandomWalk():def __init__(self,num_count = 5000):self.x_values = [0]self.y_values = [0]self.num_count = num_countdef fill_walk(self):while len(self.x_values) < self.num_count: x_step = self.get_step()y_step = self.get_step()if x_step == 0 and y_step == 0:continuex_value = x_step + self.x_values[-1]y_value = y_step + self.y_values[-1]self.x_values.append(x_value)self.y_values.append(y_value)def get_step(self):direction = choice([-1,1])distance = choice([0,1,2,3,4])step = direction * distancereturn step总结
以上是生活随笔为你收集整理的python编程从入门到实践 之 数据可视化部分总结和回顾(未完待续)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 数据结构和算法学习的开端
- 下一篇: 利用python将txt文件中的内容写入