2 Matplotlib绘图

1 Matplotlib绘图入门

1.1 简介

Matplotlib.pyplot 包含一系列绘图函数的相关函数

使用Matplotlib需要导入pyplot

import pandas as pd
import matplotlib.pyplot as plt

Matplotlib提供了两种方法来作图:状态接口和面向对象

1.2 状态接口

x = [-3, 5, 7] #准备数据的x轴坐标
y = [10, 2, 5] #准备数据的y轴坐标

plt.figure(figsize=(15,3)) #figure 创建画布  figsize指定画布大小
plt.plot(x, y) #plot 绘图
plt.xlim(-4, 8) #xlim 设置x轴坐标的范围
plt.ylim(0, 11) #ylim 设置y轴坐标的范围
plt.xlabel('X Axis',size=20) # 设置x轴标签  size字体大小
plt.ylabel('Y axis') # 设置y轴标签
plt.title('Line Plot',size=30) # 设置标题内容, size 字体大小
plt.show() #显示图片
2 Matplotlib绘图

1.3 面向对象

fig, ax = plt.subplots(figsize=(15,3))  #创建坐标轴对象
ax.plot(x, y) #调用坐标轴的绘图方法
ax.set_xlim(-4, 8) # 调用坐标轴的设置x轴上下限的方法
ax.set_ylim(0, 11) 
ax.set_xlabel('X axis') # 调用坐标轴的设置x轴标签的方法
ax.set_ylabel('Y axis',size = 20) # 调用坐标轴的设置y轴标签的方法
ax.set_title('Line Plot',size = 30) # 调用坐标轴的设置标题的方法
plt.show() 
2 Matplotlib绘图

2 matplotlib 数据可视化案例

2.1 介绍

通过Anscombe数据集说明数据可视化的重要性

  • Anscombe数据集由英国统计学家Frank Anscombe创建,数据集包含4组数据,每组数据包含两个连续变量。
  • 每组数据的平均值、方差、相关性都相同,但是当它们可视化后,就会发现每组数据的模式明显不同。

2.2 案例步骤

  1. 加载查看数据
import pandas as pd
anscombe = pd.read_csv('data/anscombe.csv')
anscombe # 查看数据
><font color = 'red'>显示结果:</font>
>
>```shell
>   dataset     x      y
>0        I  10.0   8.04
>1        I   8.0   6.95
>2        I  13.0   7.58
>3        I   9.0   8.81
>4        I  11.0   8.33
>5        I  14.0   9.96
>6        I   6.0   7.24
>7        I   4.0   4.26
>8        I  12.0  10.84
>9        I   7.0   4.82
>10       I   5.0   5.68
>11      II  10.0   9.14
>12      II   8.0   8.14
>13      II  13.0   8.74
>14      II   9.0   8.77
>15      II  11.0   9.26
>16      II  14.0   8.10
>17      II   6.0   6.13
>18      II   4.0   3.10
>19      II  12.0   9.13
>20      II   7.0   7.26
>21      II   5.0   4.74
>22     III  10.0   7.46
>23     III   8.0   6.77
>24     III  13.0  12.74
>25     III   9.0   7.11
>26     III  11.0   7.81
>27     III  14.0   8.84
>28     III   6.0   6.08
>29     III   4.0   5.39
>30     III  12.0   8.15
>31     III   7.0   6.42
>32     III   5.0   5.73
>33      IV   8.0   6.58
>34      IV   8.0   5.76
>35      IV   8.0   7.71
>36      IV   8.0   8.84
>37      IV   8.0   8.47
>38      IV   8.0   7.04
>39      IV   8.0   5.25
>40      IV  19.0  12.50
>41      IV   8.0   5.56
>42      IV   8.0   7.91
>43      IV   8.0   6.89
>```
  • 数据中的dataset 列,用来区分整个数据集中的子数据集# 取出各部分子集 dataset_1 = anscombe[anscombe['dataset']=='I'] dataset_2 = anscombe[anscombe['dataset']=='II'] dataset_3 = anscombe[anscombe['dataset']=='III'] dataset_4 = anscombe[anscombe['dataset']=='IV']
  • 查看数据的统计分布情况dataset_1.describe() 显示结果:xycount11.00000011.000000mean9.0000007.500909std3.3166252.031568min4.0000004.26000025%6.5000006.31500050%9.0000007.58000075%11.5000008.570000max14.00000010.840000dataset_2.describe() 显示结果:xycount11.00000011.000000mean9.0000007.500909std3.3166252.031657min4.0000003.10000025%6.5000006.69500050%9.0000008.14000075%11.5000008.950000max14.0000009.260000dataset_3.describe() 显示结果:xycount11.00000011.000000mean9.0000007.500000std3.3166252.030424min4.0000005.39000025%6.5000006.25000050%9.0000007.11000075%11.5000007.980000max14.00000012.740000dataset_4.describe() 显示结果:xycount11.00000011.000000mean9.0000007.500909std3.3166252.030579min8.0000005.25000025%8.0000006.17000050%8.0000007.04000075%8.0000008.190000max19.00000012.500000
  • 从数据的统计量看,变量X,Y,4个子数据集的平均值和标准差基本相同,但是平均值和标准差相同,几个数据集就完全相同么?
  • 画图展示
# 创建画布
fig = plt.figure(figsize=(16,8))
# 向画布添加子图
#子图有两行两列,位置是1
axes1 = fig.add_subplot(2,2,1)
#子图有两行两列,位置是2
axes2 = fig.add_subplot(2,2,2)
#子图有两行两列,位置是3
axes3 = fig.add_subplot(2,2,3)
#子图有两行两列,位置是4
axes4 = fig.add_subplot(2,2,4)
  • 在创建的各个坐标轴中绘制图表
axes1.plot(dataset_1['x'],dataset_1['y'],'o')
axes2.plot(dataset_2['x'],dataset_2['y'],'o')
axes3.plot(dataset_3['x'],dataset_3['y'],'o')
axes4.plot(dataset_4['x'],dataset_4['y'],'o')
fig

显示结果:

2 Matplotlib绘图
- 添加标题

```python
axes1.set_title('dataset_1') # 为子图添加标题
axes2.set_title('dataset_2')
axes3.set_title('dataset_3')
axes4.set_title('dataset_4')
fig.suptitle('Anscombe Data') #为大图添加标题
fig
```

显示结果:

2 Matplotlib绘图

3 使用matplotlib绘制统计图

  • 本小节使用tips数据集,其中包含了某餐厅服务员收集的顾客付小费的相关数据
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # ⽤来正常显⽰中⽂标签
plt.rcParams['axes.unicode_minus'] = False # ⽤来正常显⽰负号

# 加载tips数据集类
tips = pd.read_csv('data/tips.csv')
tips.head()

显示结果:

   total_bill   tip     sex smoker  day    time  size
0       16.99  1.01  Female     No  Sun  Dinner     2
1       10.34  1.66    Male     No  Sun  Dinner     3
2       21.01  3.50    Male     No  Sun  Dinner     3
3       23.68  3.31    Male     No  Sun  Dinner     2
4       24.59  3.61  Female     No  Sun  Dinner     4

3.1 单变量

  • 在统计学属于中,‘单变量’(univariate)指单个变量

3.1.1 直方图

  • 直方图是观察单个变量最常用的方法。这些值是经过”装箱”(bin)处理的
  • 直方图会将数据分组后绘制成图来显示变量的分布状况
fig = plt.figure()
axes1 = fig.add_subplot(1,1,1)
axes1.hist(tips['total_bill'],bins = 10)
axes1.set_title('Histogram of Total Bill')
axes1.set_xlabel('total bill')
axes1.set_ylabel('freq')

显示结果:

2 Matplotlib绘图

3.2 双变量

  • 双变量(bivariate)指两个变量

3.2.1 散点图

  • 散点图用于表示一个连续变量随另一个连续变量的变化所呈现的大致趋势
fig = plt.figure()
axes1 = fig.add_subplot(1,1,1)
axes1.scatter(tips['total_bill'],tips['tip'])
axes1.set_title('Scatterplot of Total Bill vs Tip')
axes1.set_xlabel('Total Bill')
axes1.set_ylabel('Tip')

显示结果:

2 Matplotlib绘图

3.3 多变量数据

  • 二维平面可以用来展示两个变量的数据,如果是多变量,比如添加一个性别变量,可以通过不同的颜色来表示
  • 还可以通过圆点的大小来区分变量的不同,但如果变量的大小区别不大,可能通过圆点大小来区分效果不是很好
def recode_sex(sex):
    if sex =='Female':
        return 0
    else:
        return 1
tips['sex_color'] = tips['sex'].apply(recode_sex)
fig = plt.figure()
axes1 = fig.add_subplot(1,1,1)
scatter = axes1.scatter(x = tips['total_bill'],y=tips['tip'],s = tips['size']*10,c=tips['sex_color'],alpha = 0.5)
legend1 = axes1.legend(*scatter.legend_elements(), loc="upper left", title="性别") # 设置图例
axes1.add_artist(legend1) # 添加图例
axes1.set_title('Total Bill vs Tip Colored by Sex and Sized by Size')
axes1.set_xlabel('total Bill')
axes1.set_ylabel('tip')

显示结果:

2 Matplotlib绘图

小结

  • Python常用绘图库
  • Matplotlib,Pandas,Seaborn,pyecharts等
  • Matplotlib绘图步骤
  • 导入Matplotlib.pyplot
  • 准备数据
  • 创建图表,坐标轴
  • 绘制图表
  • 设置标题,x,y轴标题等
数据可视化

1 Python数据可视化

2023-5-17 19:26:01

AI 知识库数学基础数据可视化

3 Pandas绘图

2023-5-17 19:33:24