七、matplotlib的使用

matplotlib的使用

点击标题即可获取文章源代码和笔记

在这里插入图片描述

二、Matplotlib
    2.1 Matplotlib之HelloWorld
        2.1.1 什么是Matplotlib - 画二维图表的python库
            mat - matrix 矩阵
                二维数据 - 二维图表
            plot - 画图
            lib - library 库
            matlab 矩阵实验室
                mat - matrix
                lab 实验室
        2.1.2 为什么要学习Matplotlib - 画图
            数据可视化 - 帮助理解数据,方便选择更合适的分析方法
            js库 - D3 echarts
            奥卡姆剃刀原理 - 如无必要勿增实体
        2.1.3 实现一个简单的Matplotlib画图
        2.1.4 认识Matplotlib图像结构
        2.1.5 拓展知识点:Matplotlib三层结构
            1)容器层
                画板层Canvas
                画布层Figure
                绘图区/坐标系
                    x、y轴张成的区域
                    2)辅助显示层
                    3)图像层
    2.2 折线图(plot)与基础绘图功能
        2.2.1 折线图绘制与保存图片
            3 设置画布属性与图片保存
                figsize : 画布大小
                dpi : dot per inch 图像的清晰度
            3 中文显示问题解决
                mac的一次配置,一劳永逸
                ubantu每创建一次新的虚拟环境,需要重新配置
                windows
                1)安装字体
                    mac/wins:双击安装
                    ubantu:双击安装
                2)删除matplotlib缓存文件
                3)配置文件
        2.2.4 多个坐标系显示-plt.subplots(面向对象的画图方法)
            figure, axes = plt.subplots(nrows=1, ncols=2, **fig_kw)
            axes[0].方法名()
            axes[1]
        2.2.5 折线图的应用场景
            某事物、某指标随时间的变化状况
            拓展:画各种数学函数图像
2.3.1 常见图形种类及意义
    折线图plot
    散点图scatter
        关系/规律
    柱状图bar
        统计/对比
    直方图histogram
        分布状况
    饼图pie π
        占比
    2.3.2 散点图绘制
    2.4 柱状图(bar)
        2.4.1 柱状图绘制
    2.5 直方图(histogram)
        2.5.1 直方图介绍
            组数:在统计数据时,我们把数据按照不同的范围分成几个组,分成的组的个数称为组数
            组距:每一组两个端点的差
            已知 最高175.5 最矮150.5 组距5
            求 组数:(175.5 - 150.5) / 5 = 5
        2.5.2 直方图与柱状图的对比
            1. 直方图展示数据的分布,柱状图比较数据的大小。
            2. 直方图X轴为定量数据,柱状图X轴为分类数据。
            3. 直方图柱子无间隔,柱状图柱子有间隔
            4. 直方图柱子宽度可不一,柱状图柱子宽度须一致
        2.5.3 直方图绘制
            x = time
            bins 组数 = (max(time) - min(time)) // 组距
            3 直方图注意点
    2.6 饼图(pie)
        %1.2f%%
        print("%1.2f%%")
import matplotlib.pyplot as plt
%matplotlib inline
plt.figure()
plt.plot([1,2,3,4,5,6,7],[17,17,18,15,11,11,13])
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-n1xZv4n5-1592962893775)(output_1_0.png)]

折线图绘制与显示

#展示上海一周的天气,比如从星期一到星期日的天气温度如下
# 1. 创建画布
# figsize:指定图片的长宽
# dpi:指定图像的清晰度
plt.figure(figsize=(20,8),dpi=280)
# 2. 绘制图像
plt.plot([1,2,3,4,5,6,7],[17,17,18,15,11,11,13])

# 保存图像
plt.savefig("fig01.png")

# 3. 显示图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tpiSGCEw-1592962893778)(output_3_0.png)]

  • 注意:plt.show()会释放figure资源,如果在显示图像之后保存图片,将只能保存空白的图片

案例:显示温度变化情况(辅助显示层)

需求:画出某城市11点到12点1小时内每分钟的温度变化折线图,温度范围在15度~18度

import random
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
y_shanghai
[16.762333158978358,
 16.943581178301798,
 17.21289155110738,
 17.304877451487915,
 16.498088429709327,	
 			...
 15.54547871676703,
 17.524143671682424,
 17.978133652214485,
 17.370197846502908]
import random

# 1. 准备数据 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]

# 2. 创建画布
plt.figure(figsize=(22,8),dpi=100)

# 3. 绘制图像
plt.plot(x,y_shanghai)

# 4. 显示图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-b24e7xFy-1592962893779)(output_8_0.png)]

2.添加自定义x,y刻度

import random

# 1. 准备数据 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]

# 2. 创建画布
plt.figure(figsize=(22,8),dpi=100)

# 3. 绘制图像
plt.plot(x,y_shanghai)

# 修改x,y刻度
plt.xticks(range(0,60,5))
plt.yticks(range(0,40,5))

# 4. 显示图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-9MpR1gn2-1592962893780)(output_10_0.png)]

["11点{}分".format(i) for i in range(61)]
['11点0分',
 '11点1分',
 '11点2分',
 '11点3分',
 '11点4分',
 '11点5分',
 '11点6分',
	 ...
 '11点56分',
 '11点57分',
 '11点58分',
 '11点59分',
 '11点60分']
import random

# 1. 准备数据 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]

# 2. 创建画布
plt.figure(figsize=(22,8),dpi=100)

# 3. 绘制图像
plt.plot(x,y_shanghai)

# 修改x,y刻度
# 准备x的刻度说明
x_label = ["11点{}分".format(i) for i in range(61)]
plt.xticks(range(0,60,5),x_label[::5])
plt.yticks(range(0,40,5))

# 4. 显示图像
plt.show()
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 28857 missing from current font.
  font.set_text(s, 0.0, flags=flags)
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:214: RuntimeWarning: Glyph 20998 missing from current font.
  font.set_text(s, 0.0, flags=flags)
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 28857 missing from current font.
  font.set_text(s, 0, flags=flags)
D:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py:183: RuntimeWarning: Glyph 20998 missing from current font.
  font.set_text(s, 0, flags=flags)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-y61N85jB-1592962893782)(output_12_1.png)]

3.解决中文显示问题

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
import random

# 1. 准备数据 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]

# 2. 创建画布
plt.figure(figsize=(22,8),dpi=100)

# 3. 绘制图像
plt.plot(x,y_shanghai)

# 修改x,y刻度
# 准备x的刻度说明
x_label = ["11点{}分".format(i) for i in range(61)]
plt.xticks(range(0,60,5),x_label[::5])
plt.yticks(range(0,40,5))

# 4. 显示图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Y6cEPTdf-1592962893783)(output_15_0.png)]

4. 添加网格显示

import random

# 1. 准备数据 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]

# 2. 创建画布
plt.figure(figsize=(22,8),dpi=100)

# 3. 绘制图像
plt.plot(x,y_shanghai)

# 修改x,y刻度
# 准备x的刻度说明
x_label = ["11点{}分".format(i) for i in range(61)]
plt.xticks(range(0,60,5),x_label[::5])
plt.yticks(range(0,40,5))

# 添加网格显示
# grid(是否显示网格,网格线样式,网格透明度)
plt.grid(True,linestyle="--",alpha=0.5)

# 4. 显示图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XVqLhTNT-1592962893784)(output_17_0.png)]

5.添加描述信息

import random

# 1. 准备数据 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]

# 2. 创建画布
plt.figure(figsize=(22,8),dpi=100)

# 3. 绘制图像
plt.plot(x,y_shanghai)

# 修改x,y刻度
# 准备x的刻度说明
x_label = ["11点{}分".format(i) for i in range(61)]
plt.xticks(range(0,60,5),x_label[::5])
plt.yticks(range(0,40,5))

# 添加描述信息
plt.xlabel("时间")
plt.ylabel("温度")
plt.title("某城市中午11:00到12:00zip间的温度变化图示")

# 添加网格显示
# grid(是否显示网格,网格线样式,网格透明度)
plt.grid(True,linestyle="--",alpha=0.5)

# 4. 显示图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JvN8Ix1l-1592962893785)(output_19_0.png)]

再添加一个城市的温度变化(图像层)

收集到北京当天温度变化情况,温度在1度到3度。

y_beijing = [random.uniform(1,3) for i in range(61)]
y_beijing
[2.6582522879775263,
 1.2944662118583519,
 2.9128902882809036,
 2.3066941253832427,
 2.100357799277068,
...
 1.0759520914191576,
 1.3613792689673339,
 2.0180224854714215,
 2.042084118916457,
 2.8643212857317306]
import random

# 1. 准备数据 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
y_beijing = [random.uniform(1,3) for i in range(60)]

# 2. 创建画布
plt.figure(figsize=(22,8),dpi=100)

# 3. 绘制图像
plt.plot(x,y_shanghai,color='r',linestyle="--")
plt.plot(x,y_beijing,color='b')
# 修改x,y刻度
# 准备x的刻度说明
x_label = ["11点{}分".format(i) for i in range(61)]
plt.xticks(range(0,60,5),x_label[::5])
plt.yticks(range(0,40,5))

# 添加描述信息
plt.xlabel("时间")
plt.ylabel("温度")
plt.title("上海、北京中午11:00到12:00zip间的温度变化图示")

# 添加网格显示
# grid(是否显示网格,网格线样式,网格透明度)
plt.grid(True,linestyle="--",alpha=0.5)

# 4. 显示图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-TH0ZTZQx-1592962893785)(output_23_0.png)]

显示图例

import random

# 1. 准备数据 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
y_beijing = [random.uniform(1,3) for i in range(60)]

# 2. 创建画布
plt.figure(figsize=(22,8),dpi=100)

# 3. 绘制图像
plt.plot(x,y_shanghai,color='r',linestyle="--",label="上海")
plt.plot(x,y_beijing,color='b',label="北京")
# 修改x,y刻度
# 准备x的刻度说明
x_label = ["11点{}分".format(i) for i in range(61)]
plt.xticks(range(0,60,5),x_label[::5])
plt.yticks(range(0,40,5))

# 添加描述信息
plt.xlabel("时间")
plt.ylabel("温度")
plt.title("上海、北京中午11:00到12:00zip间的温度变化图示")

# 添加网格显示
# grid(是否显示网格,网格线样式,网格透明度)
plt.grid(True,linestyle="--",alpha=0.5)

# 显示图例
plt.legend(loc="best")
# plt.legend(loc=2)

# 4. 显示图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NpjyklPu-1592962893786)(output_25_0.png)]

多个坐标系显示-plt.subplots(面向对象的画图方法)

我们想要将上海和北京的天气图显示在同一个图的不同坐标系当中

import random

# 1. 准备数据 x y
x = range(60)
y_shanghai = [random.uniform(15,18) for i in x]
y_beijing = [random.uniform(1,3) for i in range(60)]

# 2. 创建画布
# plt.figure(figsize=(22,8),dpi=100)

# figure是画布对象,axes是绘图区对象
figure,axes = plt.subplots(nrows=1,ncols=2,figsize=(20,8),dpi=80)

# 3. 绘制图像
axes[0].plot(x,y_shanghai,color='r',linestyle="--",label="上海")
axes[1].plot(x,y_beijing,color='b',label="北京")

# 修改x,y刻度
# 准备x的刻度说明
x_label = ["11点{}分".format(i) for i in range(61)]
axes[0].set_xticks(range(0,60,7)) # 设置x轴刻度大小
axes[0].set_xticklabels(x_label[::7]) # 设置x轴每个刻度的名字
axes[1].set_yticks(range(0,40,7))
axes[1].set_xticklabels(x_label[::7])

# 添加描述信息
axes[0].set_xlabel("时间")
axes[0].set_ylabel("温度")
axes[0].set_title("上海中午11:00到12:00zip间的温度变化图示")
axes[1].set_xlabel("时间")
axes[1].set_ylabel("温度")
axes[1].set_title("北京中午11:00到12:00zip间的温度变化图示")


# 添加网格显示
# grid(是否显示网格,网格线样式,网格透明度)
axes[0].grid(True,linestyle="--",alpha=0.5)
axes[1].grid(True,linestyle="--",alpha=0.5)

# 显示图例
axes[0].legend(loc="best")
axes[1].legend(loc="best")
# plt.legend(loc=2)

# 4. 显示图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Y9ZjGKpy-1592962893787)(output_28_0.png)]

数学函数图像

import numpy as np

# 1. 准备数据
x = np.linspace(-10,10,1000)
y = np.sin(x)

# 2. 创建画布
plt.figure(figsize=(20,8),dpi=100)

# 3. 绘制函数图像
plt.plot(x,y)

# 添加网格显示
plt.grid()

# 4. 显示图像
plt.show
<function matplotlib.pyplot.show(*args, **kw)>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JToRaQSF-1592962893787)(output_30_1.png)]

import numpy as np

# 1. 准备数据
x = np.linspace(-10,10,1000)
y = np.cos(x)

# 2. 创建画布
plt.figure(figsize=(20,8),dpi=100)

# 3. 绘制函数图像
plt.plot(x,y)

# 添加网格显示
plt.grid()

# 4. 显示图像
plt.show
<function matplotlib.pyplot.show(*args, **kw)>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QqiSZiFT-1592962893788)(output_31_1.png)]

import numpy as np

# 1. 准备数据
x = np.linspace(-10,10,1000)
y = 2*x*x

# 2. 创建画布
plt.figure(figsize=(20,8),dpi=100)

# 3. 绘制函数图像
plt.plot(x,y)

# 添加网格显示
plt.grid(linestyle='--',alpha=0.5)

# 4. 显示图像
plt.show
<function matplotlib.pyplot.show(*args, **kw)>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xKNJb7nS-1592962893788)(output_32_1.png)]

2.3.2散点图绘制

需求:探究房屋面积和屋价格的关系

# 1. 准备数据
# 房屋面积数据
x=[225.98,247.07,253.14,457.85,241.58,301.01,20.67,288.64,163.56,120.86,207.83,342.75,147.9,53.06,224.72,29.51,21.61,483.21,245.25,399.25,343.35]

# 房屋价格数据
y=[196.63,203.88,210.75,372.74,202.41,247.61,24.9,239.34,148.32,104.15,176.84,288.23,128.79,49.64,191.74,33.1,30.74,400.02,205.35,330.64,283.45]

# 2. 创建画布
plt.figure(figsize=(20,8),dpi=100)

# 3. 绘制图像
plt.scatter(x,y)

# 3. 显示图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5VaId1er-1592962893789)(output_35_0.png)]

2.4 柱状图

需求1-对比每部电影的票房收入

# 1. 准备数据
movie_names = ['雷神3:诸神黄昏','正义联盟','东方快车谋杀案','寻梦环游记','全球风暴', '降魔传','追捕','七十七天','密战','狂兽','其它']
tickets = [73853,57767,22354,15969,14839,8725,8716,8318,7916,6764,52222]

# 2. 创建画布
plt.figure(figsize=(20,8),dpi=100)

# 3. 绘制柱状图
x_ticks = range(len(movie_names))
plt.bar(x_ticks,tickets,color=['b','r','g','y','c','m','y','k','c'])

# 修改x的刻度值
# plt.xticks(刻度的大小,刻度上的值)
plt.xticks(x_ticks,movie_names)

# 添加标题
plt.title("电影票房收入对比")

# 添加网格
plt.grid(linestyle="--",alpha=0.5)

# 4. 显示图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eZTRvJeR-1592962893790)(output_38_0.png)]

需求2-如何对比电影票房收入才更能加有说服力

比较相同天数的票房

有时候为了公平起见,我们需要对比不同电影首日和首周的票房

# 1. 准备数据
movie_name=['雷神3:诸神黄昏','正义联盟','寻梦环游记']
first_day=[10587.6,10062.5,1275.71]
first_weekend=[36224.9,34479.6,11830]

x = range(len(movie_name)) 

# 2. 创建画布
plt.figure(figsize=(20,8),dpi=100)

# 3. 绘制柱状图
plt.bar(x,first_day,width=0.2,label="首日票房")
# [i+0.2 for i in x] 这是列表生成式
plt.bar([i+0.2 for i in x],first_weekend,width=0.2,label="首周票房")

# 显示图例
plt.legend(loc="best")

# 修改刻度
plt.xticks([i+0.1 for i in x],movie_name)

# 设置标题
plt.title("对比不同电影首日和首周的票房")

# 设置表格
plt.grid(linestyle="--",alpha=0.5)

# 4. 显示图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kIpDCtS8-1592962893790)(output_42_0.png)]

2.5 直方图(histogram)

·组数:在统计数据时,我们把数据按照不同的范围分成几个组,分成的组的个数称为组数

·组距:每一组两个端点的差

直方图 VS 柱状图:

1.直方图展示数据的分布,柱状图比较数据的大小

2.直方图X轴为定量数据,柱状图X轴为分类数据。

3.直方图柱子无间隔,柱状图柱子有间隔

  • 因为直方图中的区间是连续的,因此柱子之间不存在间隙。而柱状图的柱子之间是存在间隔。

4.直方图柱子宽度可不一,柱状图柱子宽度须一致

2.5.3 直方图绘制

需求:电影时长分布状况

# 1、准备数据
time = [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]

# 2、创建画布
plt.figure(figsize=(20,8),dpi=100)

# 3、给制直方图
#通常设置组数会有相应公式:组数=极差/组距=(max-min)/组距
# plt.hist(x,组数)
distance = 2 # 组距
group_num = int((max(time)-min(time))/distance) # 组数
plt.hist(time,bins=group_num,density=True)  # density=True  则y轴显示的刻度值为频率,否则为频数

# 添加网格
plt.grid(linestyle="--", alpha=0.5)

# 添加标题
plt.title("电影时长分布状况")


# 修改x轴刻度
plt.xticks(range(min(time),max(time)+2,distance))

# 4、显示图倒
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3cbYnMSO-1592962893791)(output_54_0.png)]

2.6.2饼图绘制

需求:显示不同的电影的排片占比

# 1. 准备数据
movie_name = ['雷神3:诸神黄昏','正义联盟','东方快车谋杀案','寻梦环游记','全球风暴','降魔传','追捕','七十七天','密战','狂兽','其它']

place_count = [60605,54546,45819,28243,13270,9945,7679,6799,6101,4621,20105]


# 2. 创建画布
plt.figure(figsize=(20,8),dpi=100)


# 3. 绘制饼图
# autopct 显示百分比的格式
plt.pie(place_count,labels=movie_name, colors=['b','r','g','y','c','m','y','k','c','g','y'], autopct="%1.2f%%")

# 添加axis
plt.axis("equal")

# 显示图例
plt.legend()

plt.title("不同的电影的排片占比")


# 4. 显示图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-30WhM3Zb-1592962893792)(output_57_0.png)]

猜你喜欢

转载自blog.csdn.net/weixin_44827418/article/details/106937470
今日推荐