> For the complete documentation index, see [llms.txt](https://hanxu.gitbook.io/blogs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hanxu.gitbook.io/blogs/python/matplotlib-jiao-cheng-shu-ju-ke-shi-hua.md).

# 【matplotlib教程】数据可视化

@[TOC](https://github.com/UnderTurrets/notes/blob/master/python/文章目录/README.md)

***

## 显示中文和负号

* matplotlib默认使用英文字库，汉字会乱码，要指定中文字库

```python
matplotlib.rcParams['font.family']='simHei'  #黑体
matplotlib.pyplot.rcParams['axes.unicode_minus'] = False	# 显示负号
```

## 1.各种绘图函数

### 1.1 matplotlib.pyplot.plot

```python
def plot(*args, scalex=True, scaley=True, data=None, **kwargs):...
```

常用参数：

| 参数        | 含义                             |
| --------- | ------------------------------ |
| args1     | 横坐标数组(list,numpy数组,pandas电子表格) |
| args2     | 纵坐标数组(list,numpy数组,pandas电子表格) |
| label     | 图例名字，给一个字符串即可                  |
| color     | 颜色                             |
| linestyle | 线型                             |
| marker    | 附加点的样式                         |

参数说明：

* 若输入两个数组作为args，那么第一个参数和第二个参数的数组长度必须相同，它们是一一对应关系
* 若只输入一个数组作为args，那么matplolib会自动根据数组长度进行横坐标的索引
* 颜色、线性、点样式会在第2节中详细介绍

### 1.2 matplotlib.pyplot.scatter

```python
def scatter(
        x, y, s=None, c=None, marker=None, cmap=None, norm=None,
        vmin=None, vmax=None, alpha=None, linewidths=None, *,
        edgecolors=None, plotnonfinite=False, data=None, **kwargs):...
```

常用参数：

| 参数     | 含义                             |
| ------ | ------------------------------ |
| x      | 横坐标数组(list,numpy数组,pandas电子表格) |
| y      | 纵坐标数组(list,numpy数组,pandas电子表格) |
| s      | 点的大小                           |
| marker | 点的样式                           |
| label  | 图例名字，给一个字符串即可                  |
| color  | 颜色                             |

参数说明：

* x参数和y参数的数组长度必须相同，一一对应
* s表示点的大小，默认 20，也可以是个数组，数组每个参数为对应点的大小
* 颜色、线性、点样式会在第2节中详细介绍

### 1.3 matplotlib.pyplot.bar

```python
def bar(
        x, height, width=0.8, bottom=None, *, align='center',
        data=None, **kwargs):...
```

常用参数：

| 参数          | 含义                   |
| ----------- | -------------------- |
| x           | 数组，柱形图的 x 轴数据        |
| height      | 数组，柱形图的 y 轴数据        |
| width       | 柱形图的宽度               |
| bottom      | height 坐标的偏移量，默认 0   |
| align       | 柱形图与 x 坐标的对齐方式       |
| color       | 颜色                   |
| label       | 图例名字，给一个字符串即可        |
| tick\_label | 用来替代 x 轴数据的字符串或字符串数组 |

参数说明：

* x参数和height参数的数组长度必须相同，一一对应
* width 表示柱的宽度，也可以是个数组，对应每条柱的横向宽度
* bottom表示height坐标的偏移量，也可以是个数组，对应每条柱的y偏移量
* align可选参数：中心对齐"center"，左对齐"edge"
* tick\_label可以替代x轴的数字，也可以是个数组，对应每条柱的x轴位置
* 颜色会在第2节中详细介绍

下面是一个在一张图上画出两幅柱状图的例子：

```python
import numpy as np
import matplotlib.pyplot as plt
# 数据
x = np.arange(4)
Bj = [52, 55, 63, 53]
Sh = [44, 66, 55, 41]
bar_width = 0.3
# 绘图 x 表示 从那里开始
plt.bar(x, Bj, bar_width)
plt.bar(x+bar_width, Sh, bar_width, align="center")
# 展示图片
plt.show()
```

### 1.4 matplotlib.pyplot.pie

```python
def pie(
        x, explode=None, labels=None, colors=None, autopct=None,
        pctdistance=0.6, shadow=False, labeldistance=1.1,
        startangle=0, radius=1, counterclock=True, wedgeprops=None,
        textprops=None, center=(0, 0), frame=False,
        rotatelabels=False, *, normalize=True, hatch=None, data=None):
```

常用参数：

| 参数      | 含义                     |
| ------- | ---------------------- |
| x       | 数组，用于绘制饼图的数据，表示每个扇形的面积 |
| explode | 数组，表示各个扇形之间的间隔         |
| labels  | 列表，各个扇形的标签             |
| colors  | 数组，表示各个扇形的颜色           |
| autopct | 字符串，设置饼图内各个扇形百分比显示格式   |
| radius  | 设置饼图的半径                |

参数说明：

* x参数，labels参数，colors参数的数组长度必须相同，一一对应
* explode决定图形显示的方式
* autopct举例：%d%% 整数百分比，%0.1f 一位小数， %0.1f%% 一位小数百分比， %0.2f%% 两位小数百分比

### 1.5 matplotlib.pyplot.hist

```python
def hist(
        x, bins=None, range=None, density=False, weights=None,
        cumulative=False, bottom=None, histtype='bar', align='mid',
        orientation='vertical', rwidth=None, log=False, color=None,
        label=None, stacked=False, *, data=None, **kwargs):...
```

常用参数：

| 参数     | 含义             |
| ------ | -------------- |
| x      | 数组，表示要绘制直方图的数据 |
| bins   | 直方图的箱数         |
| colors | 颜色             |
| label  | 图例             |

参数说明：

* bins举例说明：如果 bins 参数为 30，这意味着将数据范围分成 30 个等宽的区间，然后统计每个区间内数据的频数。
* 图例、颜色等，会在第2节中详细介绍

## 2.绘图样式

### 2.1 轴标签和标题

#### 轴标签（matplotlib.pyplot.xlabel与matplotlib.pyplot.ylabel）

```python
def xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs):...
def ylabel(ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs):...
```

* loc参数只有`"left"`, `"center"` , `"right "`可选

#### 标题

```python
def title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs):
```

* loc参数只有`"left"`, `"center"` , `"right "`可选

### 2.2 图例位置（matplotlib.pyplot.legend）

* **在绘图时指定好label图例后，如果不使用matplotlib.pyplot.legend函数指定图例位置，图例是不会显示的**

```python
def legend(*args, **kwargs):...
```

* loc参数如下：

| 可选参数             |
| ---------------- |
| `'upper right'`  |
| `'upper left'`   |
| `'lower left'`   |
| `'lower right'`  |
| `'right'`        |
| `'center left'`  |
| `'center right'` |
| `'lower center'` |
| `'upper center'` |
| `'center'`       |

### 2.3 可选颜色(color)

常用颜色如下：

| 颜色标记  | 描述 |
| ----- | -- |
| `'r'` | 红色 |
| `'g'` | 绿色 |
| `'b'` | 蓝色 |
| `'c'` | 青色 |
| `'m'` | 品红 |
| `'y'` | 黄色 |
| `'k'` | 黑色 |
| `'w'` | 白色 |

### 2.4 线型(linestyle)

常用线型如下：

| 线型标记   | 描述  |
| ------ | --- |
| `'-'`  | 实线  |
| `':'`  | 点虚线 |
| `'--'` | 破折线 |
| `'-.'` | 点划线 |

### 2.5 点的样式(marker)

常用样式如下：

| 可选markder | 样式                                                                                        | 描述    |
| --------- | ----------------------------------------------------------------------------------------- | ----- |
| `"."`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker1.png)  | 点     |
| `","`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker2.png)  | 像素点   |
| `"o"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker3.png)  | 实心圆   |
| `"v"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker4.png)  | 下三角   |
| `"^"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker5.png)  | 上三角   |
| `"<"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker6.png)  | 左三角   |
| `">"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker7.png)  | 右三角   |
| `"1"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker8.png)  | 下三叉   |
| `"2"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker9.png)  | 上三叉   |
| `"3"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker10.png) | 左三叉   |
| `"4"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker11.png) | 右三叉   |
| `"8"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker12.png) | 八角形   |
| `"s"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker13.png) | 正方形   |
| `"p"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker14.png) | 五边形   |
| `"P"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker15.png) | 填充的加号 |
| `"*"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker16.png) | 星号    |
| `"h"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker17.png) | 六边形1  |
| `"H"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker18.png) | 六边形2  |
| `"+"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker19.png) | 加号    |
| `"x"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker20.png) | 乘号    |
| `"X"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker21.png) | 填充的乘号 |
| `"D"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker22.png) | 菱形    |
| `"d"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker23.png) | 瘦菱形   |
| `"\|"`    | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker24.png) | 竖线    |
| `"_"`     | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker25.png) | 横线    |
| `4`       | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker26.png) | 左箭头   |
| `5`       | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker27.png) | 右箭头   |
| `6`       | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker28.png) | 上箭头   |
| `7`       | ![](https://cdn.jsdelivr.net/gh/UnderTurrets/ImageHosting@master/matplotlib_marker29.png) | 下箭头   |

## 3.画布管理与多图

### 3.1 `subplots`创建一张画布上的多图

```python
def subplots(nrows=1, ncols=1, *, sharex=False, sharey=False, squeeze=True,
             width_ratios=None, height_ratios=None,
             subplot_kw=None, gridspec_kw=None, **fig_kw):...
```

参数说明：

* nrows表示子图的行数，ncols表示子图的列数

返回值说明：

* 返回一个有2个元素的元组，分别为fig和ax。
* fig为这张画布
* ax为子图列表，想在第一张图上画折线图：**调用ax\[0].plot**

### 3.2 `subplot`创建一张画布上的多图

```python
def subplot(*args, **kwargs):
```

使用说明

* 输入`plt.subplot(2,2,1)`后，表明此时选定2行2列的一共4张子图中的第1张子图
* 此时调用`plt.plt`，就可以在第1张子图上绘图
* 切换子图时，输入`plt.subplot(2,2,2)`后，表明切换到第2张子图

### 3.3 清理

* 清理一张图上所有内容：

```python
plt.cla()
```

* 清理一张画布上的所有图：

```python
plt.clf() 
```

### 3.4 画布尺寸设置

```python
fig = plt.figure(figsize=(16, 6),dpi=100)
```

以上设置了一张宽度16英寸，高度6英寸的画布，且每英寸的像素个数为100，也就是说此图片的宽高是1600x600。大家可以自行修改想要的数值。

```python
fig.tight_layout()
```

以上这行指令用于**在所有子图都绘制完毕后自动调整子图之间的位置**，防止子图的轴标签被遮挡。

### 动态图

1. 先开启交互模式，然后提前展示画布

```python
plt.ion()
plt.show()
```

2. 在每轮绘制前先进行清理，然后停留

```python
plt.cla()
plt.plot(...)
plt.pause(0.001)
```
