Matplotlib基础
2024-09-11 16:03:49

Matplotlib基础

img

Matplotlib是一个用于Python编程语言的绘图库,它提供了一个面向对象的API,可以生成多种静态、交互式和动画可视化。Matplotlib可以用来创建高质量的图表,如线图、散点图、条形图、饼图、柱状图、误差线图、箱线图、3D 图表等等。

第一章 课程绪论

1.1 数据分析及可视化概念

数据分析是指用适当的统计分析方法对收集来的大量数据进行分析,提取有用信息和形成结论而对数据加以详细研究和概括总结的过程
收集数据 - 提取信息 - 形成结论

1708737863435

借助图形化手段表示数据,即为数据可视化的过程。

1.2 数据分析可视化流程

(1).定义分析目标
(2).数据采集及预处理
(3).数据分析挖掘
(4).数据可视化

1708737927033

数据清洗:数据清洗是指发现并纠正数据文件中可识别的错误的最后一道程序,包括检查数据一致性,处理无效值和缺失值等。

1.3 数据分析可视化案例

数据分析常用于商业决策,挖掘消费模式,优化资源配置以达到利益最大化。为了使数据更加直观清晰的呈现在人们面前,我们需要考虑用合适的方式和方法对数据进行可视化处理

(1)电影院以电影放映时间和入座率的时间序列模型进行排片
(2)网店挖掘商品售卖记录进行更科学的定价
(3)城市根据交通情况绘制热力图,优化出行效率。

1708738146121

1708738183255

1708738190553

1.4 常见的可视化形式及工具

1.4.1 可视化形式:

统计图 (直方图,折线图,饼图)

1708738430263

分布图 (热力图,散点图,气泡图)

1708738580180

1.4.2 常用工具

分类 软件名称
分析工具 pandas,SciPy,numpy,sklearn
绘图工具 matplotlib, Pychart, reportlab
平台工具 Jupyter Notebook,PyCharm

Matplotlib 是 Python 的绘图库。它可与 NumPy 一起使用提供了一种有效的 MatLab 开源替代方案。 它也可以和图形工具包一起使用,如 PyQt和 wxPython。

1708738772150

An Overview of Jupyter Notebooks - Software Engineering Daily

Jupyter Notebook是一个交互式笔记本,支持运行 40 多种编程语言。其本质是一个 Web 应用程序,便于创建和共享文学化程序文档,支持实时代码,数学方程,可视化和 markdown用途包括:数据清理和转换,数值模拟,统计建模,机器学习等等。

第二章 环境安装

2.1 安装Anaconda

Anaconda是专业的数据科学计算环境,已经集成绝大部分包和工具,可以用于在同一个机器上安装不同版本的软件包及其依赖,并能够在不同的环境之间切换,不需要多余调试,使用方便。

Anaconda官网:https://www.anaconda.com/

2.2 配置使用Jupyter Notebook

Jupyter Notebook是基于网页的用于交互计算的应用程序。其可被应用于全过程计算:开发、文档编写、运行代码和展示结果。

  • conda创建新的python环境并启用
  • conda安装Jupyter Notebook
  • 启动Jupyter Notebook

2.2.1 配置

在Anaconda Prompt输入如下命令:

1
2
3
4
conda create -n myPython python=3.7
conda activate myPython
conda install jupyter
jupyter notebook

2.3 安装matplotlib

Matplotlib 是一个 Python 的 2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形。

  • 启用conda环境
  • 安装matplotlib
1
pip install matplotlib
  • 绘制第一个图形
1
2
3
4
5
6
7
8
9
import matplotlib
import matplotlib.pyplot as plt

%matplotlib inline

x = [1, 2]
y = [3, 4]
plt.bar(x, y)
plt.show()

第三章 matplotlib入门

3.1 matplotlib配置讲解

3.1.1 matplotlib.rcParams

rcParams是matplotlib存放设置的字典,修改字典键值以改变matplotlib绘图的相关设置。

https://matplotlib.org/api/matplotlib_configuration_api.html

若不进行基本配置,可能会出现各种小问题,例如无法正常显示中文等。

matplotlib.rcParams常用基本配置

1
2
3
4
5
plt.rcParams['font.sans-serif'] = ['SimHei']  # 中文支持
plt.rcParams['axes.unicode_minus'] = False # 正常显示负号
plt.rcParams['lines.linewidth'] = 5 # 设置线条宽度
plt.rcParams['lines.color'] = 'red' # 设置线条颜色
plt.rcParams['lines.linestyle'] = '-' # 设置线条样式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import matplotlib
import matplotlib.pyplot as plt
import matplotlib as mpl
%matplotlib inline

x = [1, 2]
y = [3, 4]

plt.rcParams['font.sans-serif'] = ['SimHei'] # 中文支持
plt.rcParams['axes.unicode_minus'] = False # 正常显示负号
plt.rcParams['lines.linewidth'] = 5 # 设置线条宽度
plt.rcParams['lines.color'] = 'red' # 设置线条颜色
plt.rcParams['lines.linestyle'] = '-' # 设置线条样式

plt.title('中文标题')
plt.plot(x, y)
plt.show()

3.2 绘制直方图,条形图,折线图和饼图

直方图又称质量分布图,是一种统计报告图,由一系列高度不等的纵向条纹或线段表示数据分布的情况。

1708741583297

3.2.1 绘制直方图:plt.hist(data)

1
2
3
4
5
6
7
8
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline

height = [168, 155, 182, 170, 173, 161, 155, 173, 176, 181, 166, 172, 170]
bins = range(150, 191, 5)
plt.hist(height, bins = bins)
plt.show()

3.2.2 绘制条形图:plt.bar(X,Y)

条形图是用宽度相同的条形的高度或长短来表示数据多少的图形。

1708741842764

1
2
3
4
5
6
7
8
import matplotlib.pyplot as plt
%matplotlib inline

classes = ['class 1', 'class 2', 'class 3']
scores = [70, 80, 60]

plt.bar(classes, scores)
plt.show()

3.2.3 绘制折线图:plt.plot(X,Y)

折线图通常显示随时间而变化的连续数据,因此非常适用于体现在相等时间间隔下数据的趋势。

1708742464037

1
2
3
4
5
6
import matplotlib.pyplot as plt
%matplotlib inline

year = range(2005, 2021)
height = [157,160,162,163,167,170,173,175,174,179,182,182,182,182,182,183]
plt.plot(year,height)

3.2.4 绘制饼图:plt.pie(data)

饼图常用于显示一个数据系列中各项的大小与各项总和的比例。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import matplotlib.pyplot as plt

# 设置字体为黑体
plt.rcParams['font.sans-serif'] = ['SimHei']

# 饼图标签和数据
labels = ['房贷', '饮食', '出行', '教育']
data = [8000, 2000, 2000, 3000]

# 绘制饼图
plt.figure(figsize=(8, 8))
plt.pie(data, labels=labels, autopct='%1.1f%%')
plt.title("家庭支出分布")
plt.show()

3.3 绘制散点图和箱线图

1708742948989

3.3.1 绘制散点图:plt.scatter(x,Y)

散点图是指在回归分析中数据点在直角坐标系平面上的分布图,散点图表示因变量随自变量而变化的大致趋势,据此可以选择合适的函数对数据点进行拟合。

1708743247216

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import matplotlib.pyplot as plt
%matplotlib inline

data = [
[18.9, 10.4],
[21.3, 8.7],
[19.5, 11.6],
[20.5, 9.7],
[19.9, 9.4],
[22.3, 11],
[21.4, 10.6],
[9, 9.4],
[10.4, 9],
[9.3, 11.3],
[11.6, 8.5],
[11.8, 10.4],
[10.3, 10],
[8.7, 9.5],
[14.3, 17.2],
[14.1, 15.5],
[14, 16.5],
[16.5, 17.7],
[15.1, 17.3],
[16.4, 15],
[15.7, 18]
]

x = [item[0] for item in data]
y = [item[1] for item in data]
print(x, y)
plt.scatter(x, y)
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.title('超市商品价位与销量散点降')
plt.xlabel('价格(元)')
plt.ylabel('销量(件)')
plt.text(16, 16, '牙膏')
plt.text(10, 12, '纸巾')
plt.text(20, 10, '洗衣液')

3.3.2 绘制箱线图:plt.boxplot(X,Y)

箱线图又称为盒须图、盒式图,是一种用作显示一组数据分散情况的统计图。主要用于反映原始数据分布的特征。

1708743840018

1708744149421

1
2
3
4
5
6
7
import matplotlib.pyplot as plt
%matplotlib inline

# boxplot
data = [77, 70, 72, 89, 89, 70, 90, 87, 94, 63, 81, 99, 94, 80, 95, 67, 65, 88, 60, 67, 85, 88, 87, 75, 62, 65, 95, 62, 61, 93, 30]

plt.boxplot(data)

3.4 绘制极线图和阶梯图

3.4.1 绘制极线图:projection=’polar’

极线图用于表示极坐标下的数据分布情况,多用于显示具有一定周期性的数据。

1708744474855

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import matplotlib.pyplot as plt
%matplotlib inline

# 极径
r = [1, 2, 3, 4, 5]

#角度
theta = [
0.0,
1.5707963267948966,
3.141592653589793,
4.71238898038469,
6.283185307179586
]

ax = plt.subplot(111, projection='polar')
ax.plot(theta, r)

3.4.2 绘制阶梯图\箱线图:plt.step(X, Y)

阶梯图是一种以无规律、间歇型阶跃的方式表达数值变化的方法。它不仅可以像折线图一样反映数据发展的趋势,还可以反映数据状态的持续时间。

1708744821434

1
2
3
4
5
6
7
8
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']

year = range(2005, 2021)
print(list(year))
height = [157, 160, 162, 163, 167, 170, 173, 175, 174, 179, 182, 182, 182, 182, 182, 183]

plt.step(year, height)

第四章 matplotlib高级图形绘制

4.1 matplotlib图表参数设置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import matplotlib.pyplot as plt
%matplotlib inline

plt.rcParams['font.sans-serif'] = 'SimHei'
x = [1, 2, 3]
name = ['A班', 'B班', 'C班']
y = [80, 85, 75]
plt.bar(x, y)

plt.title('三班成绩柱状图')
plt.xlabel('班级')
plt.ylabel('成绩')
plt.xticks(x, name)
for i in range(1, 4):
plt.text(i, y[i-1] + 1, y[i-1])

4.2 绘制堆积图

堆积图常用于综合展示不同分类的指标趋势以及它们的总和的趋势。比如说,我们想看一下5名同学期末的总分情况,同时我们又想看一下这5名同学的各科成绩以及它们各自的占比,这时,我们就可以用堆积图来更高效、更简洁地展示出来,

1708746230425

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

plt.rcParams["font.sans-serif"] = ["SimHei"]

n = 5
number = ['1' '2','3','4','5']
ch = [72,80,66,77,92]
math = [62,92,72,75,88]
eng = [76,81,73,75,80]

chmath = [math[i] + ch[i] for i in range(5)]

x = np.arange(n)

plt.bar(x, ch, color='r', label='语文')
plt.bar(x, math, bottom=ch, color='g', label='数学')
plt.bar(x, eng, bottom=chmath, color='c',label='英语')

plt.ylim(0, 300)
plt.title('成绩')
plt.legend(loc='upper right')
plt.grid(axis='y', color='gray', linestyle=':', linewidth=2)
# plt.xticks(x, number)
plt.xlabel('学号')

4.3 绘制分块图

分块图可将不同数据集进行并列显示,通常可用于对同一方面的不同主体进行比较(例如用分块图来比较1班,2班,3班的各科平均分情况)

1708756029500

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
name_list = ['语文', '数学', '英语']

c1 = [81.4, 83, 87.1]
c2 = [85.6, 87.4, 90]
c3 = [78, 81.2, 86.1]

width = 0.4

x = [1, 3, 5]
plt.bar(x, c1, label='class 1', fc='r', width=width)

x = [1.4, 3.4, 5.4]
plt.bar(x, c2, label='class 2', fc='g', width=width)

x = [1.8, 3.8, 5.8]
plt.bar(x, c3, label='class 3', fc='b', width=width)

x = [1.4, 3.4, 5.4]
plt.xticks(x, name_list)
plt.legend()
plt.title('三班级成绩图')
plt.xlabel('科目')
plt.ylabel('成绩')

4.4 绘制气泡图

1708756892258

1
2
3
4
5
6
7
8
9
10
11
12
import matplotlib.pyplot as plt
%matplotlib inline

plt.rcParams['font.sans-serif'] = ['SimHei']

x = [22, 22, 23, 24, 25, 25, 26, 27, 28, 29, 30, 30, 32, 32, 32, 33, 34, 34, 35, 36, 37, 38, 38, 39, 40, 42, 43, 43, 45, 45, 46, 48, 48, 48, 50, 52, 56, 57, 60, 62]

y = [176, 186, 164, 177, 183, 194, 180, 179, 190, 170, 168, 192, 173, 178, 181, 186, 177, 187, 180, 195, 179, 186, 187, 190, 182, 184, 176, 178, 164, 185, 181, 175, 173, 172, 172, 169, 168, 182, 188, 174]

Z = [70, 220, 50, 170, 210, 270, 150, 150, 360, 150, 150, 200, 150, 170, 170, 160, 180, 460, 480, 480, 490, 300, 300, 250, 300, 250, 350, 180, 100, 250, 160, 170, 160, 180, 150, 150, 130, 180, 100, 160]

plt.scatter(x, y, s=z)

第五章 matplotlib综合系例

5.1 项目介绍

显示各省份的降雪情况

5.2 数据处理分析

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import matplotlib.pyplot as plt
%matplotlib inline

plt.rcParams['font.sans-serif'] = ['SimHei']

snow_area = [83.1,350.7,5903.3,2716.2,4446.5,2975,4615.1,8543,137.1,5073,980.8,5603.9,829.8,3367.1,7166.3,9521.1,3931.4,4479.5,2077.3,2594.3,289.3,1260.9,4649.5,1816.5,3255,176.2,2548.7,1966.9,159.4,579.9,2297.1]

total_output = [52.3,194.2,3321.9,1232.9,2492.3,2017.1,3601.6,5435.2,98.6,3360.6,656,3252.5,496.1,2029.9,4505.2,5777,2428.5,2805.2,1170.8,1420.6,149.2,806.2,2846.6,855.5,1567.7,99.8,1114.2,883.1,61.1,331.8,1474.81]

per_hectare = [6296,5538,5627,4539,5605,6780,7804,6362,7190,6624,6689,5804,5978,6028,6287,6068,6177,6262,5636,5476,5157,6394,6122,4710,4816,5663,4371,4490,3832,5721,6420]

area=['北京','天津','河北','山西','内蒙古','辽宁','吉林','黑龙江','上海','江苏','浙江','安徽','福建','江西','山东','河南','湖北','湖南','广东','广西','海南','重庆','四川','贵州','云南','西藏','陕西','甘肃','青海','宁夏','新疆']

# 最大值,均值,中位数,标准
snow_area_max = max(snow_area)
print(f'最大值:{snow_area_max}')
total_output_max = max(total_output)
per_hectare_max = max(per_hectare)

# 均值
snow_area_mean = sum(snow_area) / len(snow_area)
print(f"均值:{snow_area_mean}")
total_output_mean = sum(total_output) / len(total_output)
per_hectare_mean = sum(per_hectare) / len(per_hectare)

# 中位数
# 1 2 3 , 1 2 3 4
def median(mylist):
mylist = sorted(mylist)
if len(mylist) % 2 == 1:
return mylist[len(mylist) // 2]
else:
return (mylist[len(mylist) // 2] + mylist[len(mylist)//2-1]) / 2

snow_area_median = median(snow_area)
print(f"中位数:{snow_area_median}")
total_output_median = median(total_output)
per_hectare_median = median(per_hectare)

# 标准差
import math

def stdev(List):
mean = sum(List)/len(List)
Sum = 0
for item in List:
Sum += (item-mean)**2
Sum /= len(List)
return math.sqrt(Sum)

snow_area_stdev = stdev(snow_area)
total_output_stdev = stdev(total_output)
per_hectare_stdev = stdev(per_hectare)

5.3 可视化输出结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import matplotlib.pyplot as plt
%matplotlib inline

plt.rcParams['font.sans-serif'] = ['SimHei']

snow_area = [83.1,350.7,5903.3,2716.2,4446.5,2975,4615.1,8543,137.1,5073,980.8,5603.9,829.8,3367.1,7166.3,9521.1,3931.4,4479.5,2077.3,2594.3,289.3,1260.9,4649.5,1816.5,3255,176.2,2548.7,1966.9,159.4,579.9,2297.1]

total_output =[52.3,194.2,3321.9,1232.9,2492.3,2017.1,3601.6,5435.2,98.6,3360.6,656,3252.5,496.1,2029.9,4505.2,5777,2428.5,2805.2,1170.8,1420.6,149.2,806.2,2846.6,855.5,1567.7,99.8,1114.2,883.1,61.1,331.8,1474.81]

per_hectare=[6296,5538,5627,4539,5605,6780,7804,6362,7190,6624,6689,5804,5978,6028,6287,6068,6177,6262,5636,5476,5157,6394,6122,4710,4816,5663,4371,4490,3832,5721,6420]

area = ['北京','天津','河北','山西','内蒙古','辽宁','吉林','黑龙江','上海','江苏','浙江','安徽','福建','江西','山东','河南','湖北','湖南','广东','广西','海南','重庆','四川','贵州','云南','西藏','陕西','甘肃','青海','宁夏','新疆']

# 柱状图
plt.figure(figsize=(20, 10))
print(len(snow_area))
plt.bar(range(1, len(snow_area) + 1), snow_area)
plt.xticks(range(1, len(snow_area) + 1), area)
plt.xlabel('省份')
plt.ylabel('降雪面积')
plt.title('各省降雪面积')

plt.show()

# 饼图
plt.figure(figsize=(15, 15))
plt.pie(snow_area, labels=area, autopct="%1.1f%%")
plt.title('各省降雪面积占比图')

# 气泡图
per_hectare = [item / 20 for item in per_hectare]
plt.scatter(snow_area, total_output, s = per_hectare)
plt.xlabel('降雪面积')
plt.ylabel('降雪总量')
plt.title('降雪面积/总量/单位降雪量气泡图')