Python学习笔记(六):数据可视化

来源:互联网 发布:printf函数源码 编辑:程序博客网 时间:2024/04/28 00:59

1、使用matplotlib绘制图形

1、1  绘制折线图

import matplotlib.pyplot as pltb=[1,2,3,4,5,6,7]a=[1,4,9,16,25,36,49]plt.plot(b,a,linewidth=5)plt.title('square nums',fontsize=24)plt.xlabel('value',fontsize=14)plt.ylabel('square of value',fontsize=14)plt.tick_params(axis='both',labelsize=14)plt.show()

使用matplotlib中的模块pyplot绘制。

b为输入,a为输出,函数plot()、title()、xlabel()、ylabel()、tick_params()、show()分别为绘制图形,设置标题,设置x轴标题,设置y轴标题,设置刻度标记的大小,显示图形


1、2  使用scatter()绘制散点图

import matplotlib.pyplot as pltb=[1,2,3,4,5,6,7]a=[1,4,9,16,25,36,49]plt.scatter(b,a,s=100)plt.title('square nums',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()

scatter()中实参s设置点的大小


使用列表解析生成数据,绘制散点图

import matplotlib.pyplot as pltb=list(range(1,1001))a=[x**2 for x in b]plt.scatter(b,a,c=a,cmap=plt.cm.Blues,edgecolor='none',s=10)plt.title('square nums',fontsize=24)plt.xlabel('value',fontsize=14)plt.ylabel('square of value',fontsize=14)plt.tick_params(axis='both',which='major',labelsize=14)plt.axis([0,110,0,1000])plt.savefig('square.png',bbox_inches='tight')plt.show()

1)函数axis()设置图表的刻度范围

2)scatter()实参c=a,camp=plt.cm.Blues使用颜色映射

3)函数savefig()保存图表,第一个实参指定要以什么样的文件名保存图表,第二个实参指定将图表多余的空白区域剪裁掉


2、随机漫步


from random import choiceclass RandomWalk(object):def __init__(self,num_points=5000):self.num_points=num_pointsself.x_value=[0]self.y_value=[0]def fill_walk(self):while len(self.x_value)<self.num_points:x_direction=choice([1,-1])x_distance=choice([0,1,2,3,4])x_step=x_direction*x_distancey_direction=choice([1,-1])y_distance=choice([0,1,2,3,4])y_step=y_direction*y_distanceif x_step==0 and y_step==0:continuenext_x=self.x_value[-1]+x_stepnext_y=self.y_value[-1]+y_stepself.x_value.append(next_x)self.y_value.append(next_y)

1)函数choice([0,1,2,3,4])可随机选择列表中的数字


使用类

import matplotlib.pyplot as pltfrom random_walk import RandomWalkwhile True:keep_running=raw_input('continue walk?(y/n)')if keep_running=='n':breakelse:rw=RandomWalk(500)rw.fill_walk()#set the figure window sizeplt.figure(dpi=128,figsize=(10,6))point_numbers=list(range(rw.num_points))plt.scatter(rw.x_value,rw.y_value,c=point_numbers,cmap=plt.cm.Reds,edgecolor='none',s=2)#show start point and ending pointplt.scatter(0,0,c='green',s=10)plt.scatter(rw.x_value[-1],rw.y_value[-1],c='blue',s=10)#not show the axisplt.axes().get_xaxis().set_visible(False)plt.axes().get_yaxis().set_visible(False)plt.show()

1)函数figure()重新设置绘图窗口的尺寸,通过figsize=()元组设置窗口的宽度和高度,dpi=128,设置窗口的分辨率

2)plt.axes().get_xaxis().set_visible(False)
这条语句可隐藏坐标轴。为修改坐标轴,使用了函数plt.axes()来将每条坐标轴的可见性都设置为False。



3、使用pygal来模拟摇骰子


创建类

from random import randintclass Die():def __init__(self,num_sides=6):self.num_sides=num_sidesdef roll(self):return randint(1,self.num_sides)


1)函数randint(1,6)返回一个从1到6的随机数


模拟摇骰子

from die import Diedie=Die()results=[]for roll_num in range(100):results.append(die.roll())print(results)


统计各个点数出现的 次数

from die import Diedie=Die()results=[]for roll_num in range(1000):results.append(die.roll())print(results)point_nums=[]for value in range(1,die.num_sides+1):point_nums.append(results.count(value))print('\n')print(point_nums)

1)方法count(value)来计算值value在列表results中出现的次数


绘制各点数出现的频率直方图

from die import Dieimport pygaldie=Die()results=[]for roll_num in range(1000):results.append(die.roll())print(results)point_nums=[]for value in range(1,die.num_sides+1):point_nums.append(results.count(value))print('\n')print(point_nums)hist=pygal.Bar()hist.title='show times'hist.x_labels=['1','2','3','4','5','6']hist.x_title='results'hist.y_title='frequency of result'hist.add('die',point_nums)hist.render_to_file('die_visual.svg')


1)使用模块pygal中的Bar()类创建直方图对象hist

2)使用方法add()将一系列值添加到图表中(向他传递要给添加的值指定的标签,还有一个列表,其中包含将出现在图中的值)

3)使用方法render_to_file(‘die_visual.svg’)将这个图表渲染为一个SVG文件,使用浏览器打开即可。
















原创粉丝点击