02_python数据分析之matplotlib


上一篇: python数据分析基础介绍

1、什么是matplotlib?

学习matplotlib有两点理由:

  • 1.能将数据进行可视化,更直观的呈现
  • 2.使数据更加客观、更具说服力
    就如下图所示:
    在这里插入图片描述
    matplotlib: 最流行的Python底层绘图库,主要做数据可视化图表,名字取材于MATLAB,模仿MATLAB构建

2、matplotlib 基本要点

基本图形设置

'''
matplotlib.pyplot模块
	1、折线图和散点图plot  plot(x轴数据,y轴数据,展现形式),参数是可以叠加的
		颜色参数:
			c-cyan--青色
			r-red--红色
			m-magente--品红
			g-green--绿色
			b-blue--蓝色
			y-yellow--黄色
			k-black--黑色
			w-white--白色
		线条样式:
			-  直线
			-- 虚线
			-. -.式
			:  细小虚线
		点的样式:
			s--方形
			h--六角形
			H--六角形
			*--星形
			+--加号
			x--x形
			d--菱形
			D--菱形
			p--五角星
	2、直方图hist
		随机数的生成
		直方图绘制 hist(data,sty,histtype)  # 数据 形式 轮廓参数
	3、子图绘图
		subplot(2,2,1)
	4、可视化分析案例
		读取和讯博客的数据并可视化分析


'''
'''
import matplotlib.pyplot as pyl
import numpy as np

# 1、折线图和散点图plot
x=[1,2,3,4,8]
y=[5,7,2,1,5]
'''

'''
pyl.plot(x,y)          # 折线图
pyl.show()
pyl.plot(x,y,'o')      # 散点图,会叠加
pyl.show()

pyl.plot(x,y,'oc')     # 青色的散点图
pyl.show()

pyl.plot(x,y,'-')      # 直线
pyl.show()

pyl.plot(x,y,'--')       # 虚线
pyl.show()

pyl.plot(x,y,'-.')       # 虚线
pyl.show()

pyl.plot(x,y,':')       # 细小虚线
pyl.show()

pyl.plot(x,y,'*')       # 星形
pyl.show()

pyl.plot(x,y,'d')       # 菱形
pyl.show()

pyl.plot(x,y,'h')       # 六角形
pyl.show()
'''

'''
pyl.plot(x,y)
x2=[1,3,6,8,10,12,19]
y2=[1,6,9,10,19,23,35]
pyl.plot(x2,y2)

pyl.title("show")         # 添加标题
pyl.xlabel("ages")        # 添加x轴标题
pyl.ylabel("temp")        # 添加y轴标题
pyl.xlim(0,20)            # 设置x轴范围
pyl.ylim(0,35)            # 设置y轴范围
pyl.show()
'''

'''
# 2、直方图hist
# 随机数的生成
import numpy as np
data=np.random.random_integers(1,20,10) #(最小值,最大值,个数) 生成随机整数
# print(data)
data2=np.random.normal(5.0,2.0,10) # (均值,西格玛,个数) 生成正态分布的随机数
# print(data2)

data3=np.random.normal(10.0,1.0,10000)
# pyl.hist(data3)
# pyl.show()

data4=np.random.random_integers(1,25,1000)
# print(data4)
# pyl.hist(data4)
sty=np.arange(1,30,2)
# pyl.hist(data4,sty)
# pyl.hist(data4,sty,histtype='stepfilled')
# pyl.hist(data4,histtype='stepfilled')
# pyl.show()
# 更多随机数生成更多知识参考http://www.mamicode.com/info-detail-507676.html

#3、柱状图
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt

num_list = [1.5, 0.6, 7.8, 6]
plt.bar(range(len(num_list)), num_list)
plt.show()

# 4、子图绘图
pyl.subplot(2,2,1)
x1=[1,2,3,4,5]
y1=[5,3,5,23,5]
pyl.plot(x1,y1)

pyl.subplot(2,2,2)
x2=[5,2,3,8,6]
y2=[7,9,12,12,3]
pyl.plot(x2,y2)

pyl.subplot(2,1,2)
x3=[5,6,7,10,19,20,29]
y3=[6,2,4,21,5,1,5]
pyl.plot(x3,y3)
pyl.show()

'''
'''

在这里插入图片描述
由上图可知:每个红色的点是坐标,把5个点的坐标连接成一条线,组成了一个折线图。

那么到底如何把它通过代码画出来呢?
通过下面的小例子我们来看一下matplotlib该如何简单的使用

假设一天中每隔两个小时(range(2,26,2))的气温(℃)分别是[15,13,14.5,17,20,25,26,26,27,22,18,15]
在这里插入图片描述
具体代码如下:

# coding=utf-8
from matplotlib import pyplot as plt
# 导入数据
x = range(2,26,2)
y = [15,13,14.5,17,20,25,26,26,27,22,18,15]

# 设置图片大小
plt.figure(figsize=(20,8),dpi=80)
# 绘图
plt.plot(x,y)
#设置x轴的刻度
_xtick_labels = [i/2 for i in range(4,49)]
plt.xticks(range(1,27))
plt.yticks(range(min(y),max(y)+1))
#保存
plt.savefig("./t1.png")
#展示图形
plt.show()

结果图如下:
在这里插入图片描述
但是目前存在以下几个问题:

  1. 设置图片大小(想要一个高清无码大图)
  2. 保存到本地
  3. 描述信息,比如x轴和y轴表示什么,这个图表示什么
  4. 调整x或者y的刻度的间距
  5. 线条的样式(比如颜色,透明度等)
  6. 标记出特殊的点(比如告诉别人最高点和最低点在哪里)
  7. 给图片添加一个水印(防伪,防止盗用)
    在这里插入图片描述
    在这里插入图片描述
    那么问题来了:
    如果列表a表示10点到12点的每一分钟的气温,如何绘制折线图观察每分钟气温的变化情况?
    a= [random.randint(20,35) for i in range(120)]
    在这里插入图片描述
    上面的代码绘制的图中中文显示不出来,如何解决呢?
    在这里插入图片描述
    设置中文显示的代码截图
    在这里插入图片描述
    在这里插入图片描述
    那么x轴y轴和当前图形到底表示什么是不是应该明确一下呢?这就需要给图像添加描述信息。
    在这里插入图片描述
    在这里插入图片描述
    上图的完整代码如下:
# coding=utf-8
from matplotlib import pyplot as plt
import random
import matplotlib
from matplotlib import font_manager

# # windws和linux设置字体的放
# font = {'family' : 'MicroSoft YaHei',
#         'weight': 'bold',
#         'size': 'larger'}
# matplotlib.rc("font",**font)
# # matplotlib.rc("font",family='MicroSoft YaHei',weight="bold")

#另外一种设置字体的方式,实例化一个字体对象python
my_font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/arphic/ukai.ttc")

# 数据
x = range(0,120)
y = [random.randint(20,35) for i in range(120)]

# 设置图片大小
plt.figure(figsize=(20,8),dpi=80)

# 绘图
plt.plot(x,y)

#调整x轴的刻度
_xtick_labels = ["10点{}分".format(i) for i in range(60)]
_xtick_labels += ["11点{}分".format(i) for i in range(60)]

# 取步长,数字和字符串一一对应,数据的长度一样
plt.xticks(list(x)[::3],_xtick_labels[::3],rotation=45,fontproperties=my_font) #rotaion旋转的度数

#添加描述信息
plt.xlabel("时间",fontproperties=my_font)
plt.ylabel("温度 单位(℃)",fontproperties=my_font)
plt.title("10点到12点每分钟的气温变化情况",fontproperties=my_font)

#保存
plt.savefig("./t2.png")

plt.show()

动手练习 1
假设大家在30岁的时候,根据自己的实际情况,统计出来了你和你同桌各自从11岁到30岁每年交的女(男)朋友的数量如列表a和b,请在一个图中绘制出该数据的折线图,以便比较自己和同桌20年间的差异,同时分析每年交女(男)朋友的数量走势
a = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
b = [1,0,3,1,2,2,3,3,2,1 ,2,1,1,1,1,1,1,1,1,1]
要求:

  • y轴表示个数
  • x轴表示岁数,比如11岁,12岁等
# coding=utf-8
import matplotlib.pyplot  as plt
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/arphic/ukai.ttc")

# 数据
y_1 = [1,0,1,1,2,4,3,2,3,4,4,5,6,5,4,3,3,1,1,1]
y_2= [1,0,3,1,2,2,3,3,2,1 ,2,1,1,1,1,1,1,1,1,1]
x = range(11,31)

# 设置图形大小
plt.figure(figsize=(20,8),dpi=80)

plt.plot(x,y_1,label="自己",color="r",alpha=0.5)
plt.plot(x,y_2,label="同桌",color="y",linestyle="--",alpha=0.5)

# 设置x轴刻度
_xtick_labels = ["{}岁".format(i) for i in x]
plt.xticks(x,_xtick_labels,fontproperties=my_font)
plt.yticks(range(0,9))

# 添加标题
plt.xlabel("年龄",fontproperties=my_font)
plt.ylabel("交友数量",fontproperties=my_font)

# 绘制网格
plt.grid(alpha=0.5)

# 添加图例
plt.legend(prop=my_font,loc='best') #注意参数是prop,不要写错

#保存
plt.savefig("./t4.png")

# 展示
plt.show()

绘图结果
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
这个实现不难,可以百度。
总结
必须掌握的知识:

  1. 绘制了折线图(plt.plot)
  2. 设置了图片的大小和分辨率(plt.figure)
  3. 实现了图片的保存(plt.savefig)
  4. 设置了xy轴上的刻度和字符串(xticks)
  5. 解决了刻度稀疏和密集的问题(xticks)
  6. 设置了标题,xy轴的lable(title,xlable,ylable)
  7. 设置了字体(font_manager. fontProperties,matplotlib.rc)
  8. 在一个图上绘制多个图形(plt多次plot即可)
  9. 为不同的图形添加图例

3、matplotlib 的散点图、直方图、柱状图

matplotlib能够绘制折线图,散点图,柱状图,直方图,箱线图,饼图等。但是,我们需要知道不同的统计图到底能够表示出什么,以此来决定选择哪种统计图来更直观的呈现我们的数据。

3.1 对比常用统计图

在这里插入图片描述
折线图的更多应用场景

  • 呈现公司产品(不同区域)每天活跃用户数
  • 呈现app每天下载数量
  • 呈现产品新功能上线后,用户点击次数随时间的变化
  • 呈现员工每天上下班时间

3.2 绘制散点图

假设通过爬虫你获取到了北京2016年3,10月份每天白天的最高气温(分别位于列表a,b),那么此时如何寻找出气温和随时间(天)变化的某种规律?
a=[11,17,16,11,12,11,12,6,6,7,8,9,12,15,14,17,18,21,16,17,20,14,15,15,15,19,21,22,22,22,23]
b = [26,26,28,19,21,17,16,19,18,20,20,19,22,23,17,20,21,20,22,15,11,15,5,13,17,10,11,13,12,13,6]

数据来源:http://lishi.tianqi.com/beijing/index.html
在这里插入图片描述
实现代码:

# coding=utf-8
from matplotlib import pyplot as plt
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/arphic/ukai.ttc")
y_3 = [11,17,16,11,12,11,12,6,6,7,8,9,12,15,14,17,18,21,16,17,20,14,15,15,15,19,21,22,22,22,23]
y_10 = [26,26,28,19,21,17,16,19,18,20,20,19,22,23,17,20,21,20,22,15,11,15,5,13,17,10,11,13,12,13,6]

x_3 = range(1,32)
x_10 = range(51,82)

# 设置图形大小
plt.figure(figsize=(20,8),dpi=80)

# 使用scatter方法绘制散点图,和之前绘制折线图的唯一区别
plt.scatter(x_3,y_3,label="3月份")
plt.scatter(x_10,y_10,label="10月份")

# 调整x轴的刻度
_x = list(x_3)+list(x_10)
_xtick_labels = ["3月{}日".format(i) for i in x_3]
_xtick_labels += ["10月{}日".format(i-50) for i in x_10]
plt.xticks(_x[::3],_xtick_labels[::3],fontproperties=my_font,rotation=45)

# 添加图例
plt.legend(loc="upper left",prop=my_font)

# 添加描述信息
plt.xlabel("时间",fontproperties=my_font)
plt.ylabel("温度",fontproperties=my_font)
plt.title("标题",fontproperties=my_font)

# 展示
plt.show()

# 保存
plt.savefig("./t5.png")

散点图的更多应用场景

  • 不同条件(维度)之间的内在关联关系
  • 观察数据的离散聚合程度

3.3 绘制条形图

假设你获取到了2017年内地电影票房前20的电影(列表a)和电影票房数据(列表b),那么如何更加直观的展示该数据?

a = [“战狼2”,“速度与激情8”,“功夫瑜伽”,“西游伏妖篇”,“变形金刚5:最后的骑士”,“摔跤吧!爸爸”,“加勒比海盗5:死无对证”,“金刚:骷髅岛”,“极限特工:终极回归”,“生化危机6:终章”,“乘风破浪”,“神偷奶爸3”,“智取威虎山”,“大闹天竺”,“金刚狼3:殊死一战”,“蜘蛛侠:英雄归来”,“悟空传”,“银河护卫队2”,“情圣”,“新木乃伊”,]
b=[56.01,26.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,6.86,6.58,6.23] 单位:亿

数据来源:http://58921.com/alltime/2017
在这里插入图片描述
代码1:

# coding=utf-8
from matplotlib import pyplot as plt
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/arphic/ukai.ttc")


a = ["战狼2","速度与激情8","功夫瑜伽","西游伏妖篇","变形金刚5:最后的骑士","摔跤吧!爸爸","加勒比海盗5:死无对证","金刚:骷髅岛","极限特工:终极回归","生化危机6:终章","乘风破浪","神偷奶爸3","智取威虎山","大闹天竺","金刚狼3:殊死一战","蜘蛛侠:英雄归来","悟空传","银河护卫队2","情圣","新木乃伊",]

b=[56.01,26.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,6.86,6.58,6.23]


#设置图形大小
plt.figure(figsize=(20,15),dpi=80)
#绘制条形图
plt.bar(range(len(a)),b,width=0.3,color="orange")
#设置字符串到x轴
plt.xticks(range(len(a)),a,fontproperties=my_font,rotation=90)
# 添加描述信息
plt.ylabel("票房(单位:亿元)",fontproperties=my_font)
plt.title("2017年内地电影票房top20",fontproperties=my_font)

# 保存
plt.savefig("./t6.png")

plt.show()

代码2:

# coding=utf-8
from matplotlib import pyplot as plt
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/arphic/ukai.ttc")


a = ["战狼2","速度与激情8","功夫瑜伽","西游伏妖篇","变形金刚5:最后的骑士","摔跤吧!爸爸","加勒比海盗5:死无对证","金刚:骷髅岛","极限特工:终极回归","生化危机6:终章","乘风破浪","神偷奶爸3","智取威虎山","大闹天竺","金刚狼3:殊死一战","蜘蛛侠:英雄归来","悟空传","银河护卫队2","情圣","新木乃伊",]

b=[56.01,26.94,17.53,16.49,15.45,12.96,11.8,11.61,11.28,11.12,10.49,10.3,8.75,7.55,7.32,6.99,6.88,6.86,6.58,6.23]

#设置图形大小
plt.figure(figsize=(20,15),dpi=80)
#绘制条形图
plt.barh(range(len(a)),b,height=0.3,color="orange")
#设置字符串到y轴
plt.yticks(range(len(a)),a,fontproperties=my_font)
# 添加描述信息
plt.xlabel("票房(单位:亿元)",fontproperties=my_font)
plt.title("2017年内地电影票房top20",fontproperties=my_font)
plt.grid(alpha=0.3)

plt.savefig("./t6_1.png")

plt.show()

假设你知道了列表a中电影分别在2017-09-14(b_14), 2017-09-15(b_15), 2017-09-16(b_16)三天的票房,为了展示列表中电影本身的票房以及同其他电影的数据对比情况,应该如何更加直观的呈现该数据?

a = [“猩球崛起3:终极之战”,“敦刻尔克”,“蜘蛛侠:英雄归来”,“战狼2”]
b_16 = [15746,312,4497,319]
b_15 = [12357,156,2045,168]
b_14 = [2358,399,2358,362]

数据来源: http://www.cbooo.cn/movieday
在这里插入图片描述

# coding=utf-8
from matplotlib import pyplot as plt
from matplotlib import font_manager

my_font = font_manager.FontProperties(fname="/usr/share/fonts/truetype/arphic/ukai.ttc")

a = ["猩球崛起3:终极之战", "敦刻尔克", "蜘蛛侠:英雄归来", "战狼2"]
b_16 = [15746, 312, 4497, 319]
b_15 = [12357, 156, 2045, 168]
b_14 = [2358, 399, 2358, 362]

bar_width = 0.2

x_14 = list(range(len(a)))
x_15 = [i + bar_width for i in x_14]
x_16 = [i + bar_width * 2 for i in x_14]

# 设置图形大小
plt.figure(figsize=(20, 8), dpi=80)

plt.bar(range(len(a)), b_14, width=bar_width, label="9月14日")
plt.bar(x_15, b_15, width=bar_width, label="9月15日")
plt.bar(x_16, b_16, width=bar_width, label="9月16日")

# 设置图例
plt.legend(prop=my_font)

# 设置x轴的刻度
plt.xticks(x_15, a, fontproperties=my_font)  # 电影名称也对应上去

# 保存
plt.savefig("./t7.png")

plt.show()

条形图的更多应用场景

  • 数量统计
  • 频率统计(市场饱和度)

3.4 绘制直方图

假设你获取了250部电影的时长(列表a中),希望统计出这些电影时长的分布状态(比如时长为100分钟到120分钟电影的数量,出现的频率)等信息,你应该如何呈现这些数据?

a=[131, 98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119, 128, 121, 142, 127, 130, 124, 101, 110, 116, 117, 110, 128, 128, 115, 99, 136, 126, 134, 95, 138, 117, 111,78, 132, 124, 113, 150, 110, 117, 86, 95, 144, 105, 126, 130,126, 130, 126, 116, 123, 106, 112, 138, 123, 86, 101, 99, 136,123, 117, 119, 105, 137, 123, 128, 125, 104, 109, 134, 125, 127,105, 120, 107, 129, 116, 108, 132, 103, 136, 118, 102, 120, 114,105, 115, 132, 145, 119, 121, 112, 139, 125, 138, 109, 132, 134,156, 106, 117, 127, 144, 139, 139, 119, 140, 83, 110, 102,123,107, 143, 115, 136, 118, 139, 123, 112, 118, 125, 109, 119, 133,112, 114, 122, 109, 106, 123, 116, 131, 127, 115, 118, 112, 135,115, 146, 137, 116, 103, 144, 83, 123, 111, 110, 111, 100, 154,136, 100, 118, 119, 133, 134, 106, 129, 126, 110, 111, 109, 141,120, 117, 106, 149, 122, 122, 110, 118, 127, 121, 114, 125, 126,114, 140, 103, 130, 141, 117, 106, 114, 121, 114, 133, 137, 92,121, 112, 146, 97, 137, 105, 98, 117, 112, 81, 97, 139, 113,134, 106, 144, 110, 137, 137, 111, 104, 117, 100, 111, 101, 110,105, 129, 137, 112, 120, 113, 133, 112, 83, 94, 146, 133, 101,131, 116, 111, 84, 137, 115, 122, 106, 144, 109, 123, 116, 111,111, 133, 150]
在这里插入图片描述
代码:

# coding=utf-8
from matplotlib import pyplot as plt
from matplotlib import font_manager

a = [131, 98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119, 128, 121, 142, 127, 130, 124,
     101, 110, 116, 117, 110, 128, 128, 115, 99, 136, 126, 134, 95, 138, 117, 111, 78, 132, 124, 113, 150, 110, 117, 86,
     95, 144, 105, 126, 130, 126, 130, 126, 116, 123, 106, 112, 138, 123, 86, 101, 99, 136, 123, 117, 119, 105, 137,
     123, 128, 125, 104, 109, 134, 125, 127, 105, 120, 107, 129, 116, 108, 132, 103, 136, 118, 102, 120, 114, 105, 115,
     132, 145, 119, 121, 112, 139, 125, 138, 109, 132, 134, 156, 106, 117, 127, 144, 139, 139, 119, 140, 83, 110, 102,
     123, 107, 143, 115, 136, 118, 139, 123, 112, 118, 125, 109, 119, 133, 112, 114, 122, 109, 106, 123, 116, 131, 127,
     115, 118, 112, 135, 115, 146, 137, 116, 103, 144, 83, 123, 111, 110, 111, 100, 154, 136, 100, 118, 119, 133, 134,
     106, 129, 126, 110, 111, 109, 141, 120, 117, 106, 149, 122, 122, 110, 118, 127, 121, 114, 125, 126, 114, 140, 103,
     130, 141, 117, 106, 114, 121, 114, 133, 137, 92, 121, 112, 146, 97, 137, 105, 98, 117, 112, 81, 97, 139, 113, 134,
     106, 144, 110, 137, 137, 111, 104, 117, 100, 111, 101, 110, 105, 129, 137, 112, 120, 113, 133, 112, 83, 94, 146,
     133, 101, 131, 116, 111, 84, 137, 115, 122, 106, 144, 109, 123, 116, 111, 111, 133, 150]

# 计算组数
d = 3  # 组距
num_bins = (max(a) - min(a)) // d
print(max(a), min(a), max(a) - min(a))
print(num_bins)

# 设置图形的大小
plt.figure(figsize=(20, 8), dpi=80)
plt.hist(a, num_bins, density=True)  # density=True 表示显示频率
# plt.hist(a,[min(a)+i*d for i in range(num_bins)])  # density=True 表示显示频率

# 设置x轴的刻度
plt.xticks(range(min(a), max(a) + d, d))

# 网格线
plt.grid()

# 保存
plt.savefig("./t8.png")

plt.show()

在这里插入图片描述
前面的问题问的是什么呢?
问的是:哪些数据能够绘制直方图

前面的问题中给出的数据都是统计之后的数据,
所以为了达到直方图的效果,需要绘制条形图

所以:一般来说能够使用plt.hist方法的的是那些没有统计过的数据

直方图更多应用场景

  • 用户的年龄分布状态
  • 一段时间内用户点击次数的分布状态
  • 用户活跃时间的分布状态

matplotlib常见问题总结

  1. 应该选择那种图形来呈现数据
  2. matplotlib.plot(x,y)
  3. matplotlib.bar(x,y)
  4. matplotlib.scatter(x,y)
  5. matplotlib.hist(data,bins,normed)
  6. xticks和yticks的设置
  7. label和titile,grid的设置
  8. 绘图的大小和保存图片
    在这里插入图片描述
    matplotlib支持的图形是非常多的,如果有其他的需求,我们可以查看一下url地址:http://matplotlib.org/gallery/index.html

4、更多的画图工具

plotly:可视化工具中的github,相比于matplotlib更加简单,图形更加漂亮,同时兼容matplotlib和pandas

使用用法:简单,照着文档写即可

文档地址: https://plot.ly/python/

下一篇:python数据分析之numpy

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值