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

1、使用matplotlib绘制图形

1、1  绘制折线图

import matplotlib.pyplot as plt

b=[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 plt

b=[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 plt

b=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 choice

class RandomWalk(object):
	def __init__(self,num_points=5000):
		self.num_points=num_points
		self.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_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_value[-1]+x_step
			next_y=self.y_value[-1]+y_step
			
			self.x_value.append(next_x)
			self.y_value.append(next_y)

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


使用类

import matplotlib.pyplot as plt

from random_walk import RandomWalk
while True:
	keep_running=raw_input('continue walk?(y/n)')
	if keep_running=='n':
		break
	else:
		rw=RandomWalk(500)
		rw.fill_walk()
		
		#set the figure window size
		plt.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 point
		plt.scatter(0,0,c='green',s=10)
		plt.scatter(rw.x_value[-1],rw.y_value[-1],c='blue',s=10)
		
		#not show the axis
		plt.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 randint

class Die():
	def __init__(self,num_sides=6):
		self.num_sides=num_sides
	
	def roll(self):
		return randint(1,self.num_sides)


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


模拟摇骰子

from die import Die

die=Die()
results=[]

for roll_num in range(100):
	results.append(die.roll())
print(results)


统计各个点数出现的 次数

from die import Die

die=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 Die
import pygal

die=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文件,使用浏览器打开即可。
















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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值