Matplotlib之pyplot在数据分析中的常用操作

做机器学习方向首先得学会点Matplotlib库的知识吧,所以我就在这做一下学习笔记,记录一下我在机器学习方向上所常用到的Matplotlib上的知识。

官方文档:网址http://matplotlib.org/api/pyplot_api.html#matplotlib后面加.pyplot.函数名便可查询对应的函数用法。

一、折线图的绘制

先上一个样例代码:

import matplotlib.pyplot as plt

plt.plot()
plt.show()

输出结果:
0
这样我们就画了一个空白的图像。

然后我们再尝试着加入数据,画二维坐标图首先需要一组二维数对(x, y),这里我随便找了一组数据作为折线图的x轴和y轴:

x_axis = [794.28818799999999,
         808.50958700000001,
         826.25461900000005,
         833.53230499999995,
         841.97451199999989,
         846.94015999999999,
         851.69061199999987,
         861.97213299999999,
         874.92434100000003,
         888.51824600000009]
y_axis = [79.877565000000004,
         99.524317000000011,
         62.525946999999995,
         57.281737,
         52.371316,
         70.615566000000001,
         47.351207000000002,
         43.719923000000001,
         40.642712000000003,
         38.535789000000001]

然后使用plt.plot()绘制折线图:

plt.plot(x_axis, y_axis)
plt.show()

输出结果如下:
【图片失效】

接下来我们进一步对图像进行细节处理:

plt.plot(x_axis, y_axis)
plt.xticks(rotation = 45)	#加入这条代码
plt.show()

输出结果(注意x轴坐标的变化,数字倾斜了45°):
【图片失效】

这样一来,如果遇到x轴位数过长以至于重叠的时候,斜着画x轴的方法就派上用场了。当然了,同理把xticks换成yticks就是改变y轴坐标的倾斜度了。

接下来我们再给这个图像加上“轴的说明”和一个“标题”。
代码如下:

plt.plot(x_axis, y_axis)
plt.xticks(rotation = 45)

#新加入的代码如下:
plt.xlabel("this is x_axis") #x轴说明
plt.ylabel("this is y_axis") #y轴说明
plt.title("this is title") #此图像的标题

plt.show()

输出结果:
【图片失效】

这样,我们就添加了x坐标轴和y坐标轴的含义以及这个图像的意义。

那么如果我想在同一个图中同时画两条折线呢?那就写plt.plot()两次呗:
既然是两条线,那就肯定再需要一组数据,这里我们就在前面的数据上每个y坐标轴值+1获得一组新数据,代码如下:

#再构造一组数据
x1_axis = x_axis.copy()
y1_axis = []
for i in y_axis:
    y1_axis.append(i+10)

有了数据就可以画图了,代码如下:

plt.plot(x_axis, y_axis, c = "r", label = "red")
plt.plot(x1_axis, y1_axis, c = "b", label = "red")
plt.legend(loc = "best")

plt.show()

输出结果:
7
下面我们来解释以下,新增的代码含义。

  1. 首先是plt.plot()中的参数c,这个是用来选择曲线颜色的,比如"r"表示"red", "b"表示"blue"等等;
  2. 其次是参数label,表示的是这条曲线的含义,就是上图中右上角那个小框框里面的解释;
  3. 最后是函数plt.legend(loc = "best")就是用来表示这个小框框应该放在哪里,里面的参数loc的值可以是'best', 'upper right', 'upper left', 'lower left', 'lower right', 'right','center left', 'center right', 'lower center', 'upper center', 'center',分别表示“最好位置”,“右上角”,“左上角”等等。

小结,以上全部的常用操作代码列举如下:

import matplotlib.pyplot as plt

#构造数据
x_axis = [794.28818799999999,
         808.50958700000001,
         826.25461900000005,
         833.53230499999995,
         841.97451199999989,
         846.94015999999999,
         851.69061199999987,
         861.97213299999999,
         874.92434100000003,
         888.51824600000009]
y_axis = [79.877565000000004,
         99.524317000000011,
         62.525946999999995,
         57.281737,
         52.371316,
         70.615566000000001,
         47.351207000000002,
         43.719923000000001,
         40.642712000000003,
         38.535789000000001]
#再构造一组数据
x1_axis = x_axis.copy()
y1_axis = []
for i in y_axis:
    y1_axis.append(i+10)

#绘图
plt.plot(x_axis, y_axis, c = "r", label = "red")
plt.plot(x1_axis, y1_axis, c = "b", label = "red")

plt.xticks(rotation = 45)

plt.xlabel("this is x_axis")
plt.ylabel("this is y_axis")
plt.title("this is title")

plt.legend(loc = "best")

plt.show()

输出结果:
11

二、子图操作

有时候我们会在一个区域中画很多个子图,这就需要我们用到子图操作了。
废话不多说,先上代码:

import matplotlib.pyplot as plt

fig = plt.figure()

ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax4 = fig.add_subplot(2,2,4)

plt.show()

输出结果:
5
解释一下上面的代码,首先我们用函数plt.figure()创建了一个区域的对象;然后我们又用函数fig.add_subplot()在这个区域里建了三个子图,至于函数fig.add_subplot()中的三个参数是什么意思,我这里用一张图来说明就够了:
4

下面我们再进一步对上面的图像做一下进阶处理:
代码如下:

fig = plt.figure(figsize=(16,8)) #再添加此代码

ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,4)

#下面画两个折线图,只对子图1和子图2填充数据
ax1.plot(x_axis, y_axis)
ax2.plot(x_axis, y_axis)

plt.show()

输出结果:
6
明显可以看到,这张图像比上面那张宽了很多,高了也很多。plt.figure(figsize=(16,8))函数中的figsize参数就表示了这个区域的长和宽。

三、条形图

条形图也就是柱状图、bar形图。

我们这里只记录一下数据分析中常用的操作,详细具体的条形图操作原理可以看一下这篇博客:
http://blog.sina.com.cn/s/blog_b09d4602010194wy.html

如图,我们最终要画一个类似这样的条形图:
12

首先,画条形图主要需要两组数据:

  1. left:bar的位置;
  2. height:bar的高度值。

所谓的“bar的位置”就是指对应的每条bar在x轴上到0点的距离,“bar的高度值”就是指对应的每条bar(柱)在y坐标轴对应的值。

我们先构造出这两组数据:

bar_positions = [1, 2, 3, 4, 5, 6] #每条bar的位置
bar_heights = [2,3,6,1,7,8] #每条bar的高度值

然后绘制bar形图:

import matplotlib.pyplot as plt

plt.bar(bar_positions, bar_heights, 0.3)
#这里的第三个参数0.3的意思是bar的粗细

plt.show()

输出结果:
14
由上面可知,条形图的画法和折线图是相似的。

下面我们仿照上面的折线图操作画一下bar形图,代码如下:

import matplotlib.pyplot as plt

#构造数据
bar_positions = [i+0.9 for i in range(6)]
bar_heights = [2,3,6,1,7,8]
#再构造一组数据
bar_positions2 = [i+1.1 for i in range(6)]
bar_heights2 = bar_heights.copy()

#绘图
plt.bar(bar_positions, bar_heights, 0.2, color = "r", label = "red")
plt.bar(bar_positions2, bar_heights2, 0.2, color = "b", label = "red")

#为每条bar写明含义
num_cols = ["first_bar", "second_bar", "third_bar", "forth_bar", "fifth_bar", "sixth_bar"]
plt.xticks(range(1,7), num_cols, rotation = 45)

plt.xlabel("this is x_axis")
plt.ylabel("this is y_axis")
plt.title("this is title")

plt.legend(loc = "best")

plt.show()

输出结果:
12.5

还有一种条形图,是横着画的,就是把函数plt.bar()换成plt.barh(),相应的bar的“位置”和“高度”对应着barh的“高度”和“宽度”,废话不多说,上代码:

import matplotlib.pyplot as plt

#构造数据
bar_positions = [1, 2, 3, 4, 5, 6]
bar_widths = [2,3,6,1,7,8]

#绘图
plt.barh(bar_positions, bar_widths, 0.5)

#为每条bar写明含义
num_cols = ["first_bar", "second_bar", "third_bar", "forth_bar", "fifth_bar", "sixth_bar"]
plt.yticks(range(1,7), num_cols)

plt.xlabel("this is x_axis")
plt.ylabel("this is y_axis")
plt.title("this is title")

plt.legend(loc = "best")

plt.show()

输出结果:
13.5

知识拓展:
下面我们用画子图的方法改进一下代码,不过这里我们使用的是另一种子图操作,其实都差不多一样,详见官方文档:
https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplots

好了,先上代码:

import matplotlib.pyplot as plt

#构造数据
bar_positions = [1, 2, 3, 4, 5, 6] 
bar_heights = [2,3,6,1,7,8] 

fig, ax = plt.subplots()
ax.bar(bar_positions, bar_heights, 0.5)
plt.show()

输出结果:
13

接下来我们继续进行图像的进阶操作,代码如下:

import matplotlib.pyplot as plt

#构造数据
bar_positions = [1, 2, 3, 4, 5, 6] 
bar_heights = [2,3,6,1,7,8] 

num_cols = ["first_bar", "second_bar", "third_bar", "forth_bar", "fifth_bar", "sixth_bar"]

fig, ax = plt.subplots()

ax.bar(bar_positions, bar_heights, 0.5)

#为每条bar写明含义
ax.set_xticks(range(1,7))
ax.set_xticklabels(num_cols, rotation = 45)

ax.set_xlabel("this is x_axis")
ax.set_ylabel("this is y_axis")
ax.set_title("this is title")

plt.show()

输出结果:
12

横着画也可以,代码如下:

import matplotlib.pyplot as plt

#构造数据
bar_positions = [1, 2, 3, 4, 5, 6] 
bar_heights = [2,3,6,1,7,8] 

fig, ax = plt.subplots()

ax.barh(bar_positions, bar_widths, 0.5)#这里把函数ax.bar()换成了ax.bar()
#下面在y坐标轴上说明每条bar的含义
ax.set_yticks(range(1,7))
ax.set_yticklabels(num_cols, rotation = 45)

ax.set_xlabel("this is x_axis")
ax.set_ylabel("this is y_axis")
ax.set_title("this is title")

plt.show()

输出结果:
112

四、散点图

画散点图和折线图差不多,只是把函数plot换成函数scatter(),当然了,散点图也能进行子图操作等等。

首先我们先画一个简单的散点图,继续使用上面的数据x_axis和y_axis:

#构造数据
x_axis = [794.28818799999999,
         808.50958700000001,
         826.25461900000005,
         833.53230499999995,
         841.97451199999989,
         846.94015999999999,
         851.69061199999987,
         861.97213299999999,
         874.92434100000003,
         888.51824600000009]
y_axis = [79.877565000000004,
         99.524317000000011,
         62.525946999999995,
         57.281737,
         52.371316,
         70.615566000000001,
         47.351207000000002,
         43.719923000000001,
         40.642712000000003,
         38.535789000000001]

然后开始绘制图像:

import matplotlib.pyplot as plt

plt.scatter(x_axis, y_axis)
plt.show()

输出结果:
11
进阶操作:

import matplotlib.pyplot as plt

plt.scatter(x_axis, y_axis, marker='x', c='r', label = "red")
plt.xlabel("this is x_axis")
plt.ylabel("this is y_axis")
plt.title("this is title")
plt.xticks(rotation = 45)

plt.legend(loc = "upper right")

plt.show()

输出结果:
222

至于子图操作和画折线图差不多,这里就不多啰嗦了。

五、直方图

直方图所用的函数就是plt.hist()了。
直方图一般用来统计一组数据中每个量的频数。

统计学中直方图定义如下:

对某一物理量在相同条件下做n次重复测量,得到一系列测量值,找出它的最大值和最小值,然后确定一个区间,使其包含全部测量数据,将区间分成若干小区间,统计测量结果出现在各小区间的频数M,以测量数据为横坐标,以频数M为纵坐标,划出各小区间及其对应的频数高度,则可得到一个矩形图,即统计直方图。

# 随便找了点数据
data = [2.7, 2.7, 2.8, 2.8, 2.9, 2.9, 2.9, 2.9, 2.9, 3.0, 3.0, 3.0, 3.0, 3.1, 3.1, 3.1, 3.2, 3.2, 3.2, 3.2, 3.2, 3.3, 3.3, 3.3, 3.3, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 3.4, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.5, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.6, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.7, 3.8, 3.8, 3.8, 3.8, 3.8, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 3.9, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.1, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.2, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.3, 4.4, 4.4, 4.4, 4.4, 4.4, 4.4, 4.4, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.5, 4.6, 4.6, 4.6, 4.6, 4.8, 4.8, 4.8]

样例代码如下:

import matplotlib.pyplot as plt
plt.hist(data)
plt.show()

输出结果:
111

plt.hist(data, bins=20)
plt.show()

输出结果:
222

plt.hist(data, range=(4,5), bins=20)
plt.show()

输出结果:
333

跟我们中学时期画的直方图一样,都需要定若干个小区间,

  • plt.hist()函数中的bins参数值就是这些小区间的个数,默认是10。
  • range=(4,5)的意思就是选取横坐标轴4到5的部分显示。

也可以为y坐标轴设置范围:

plt.hist(data, range=(4,5), bins=20)

#定义y坐标轴范围为0到50
plt.ylim(0,50)

plt.show()

输出结果如下:
444

六、盒图

继续使用上面的数据,代码如下:

plt.boxplot(data)
plt.show()

输出结果:
555

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值