# Matplotlib 参数及元素

## linestyle或ls 线条风格

| 参数        | 描述    |
| --------- | ----- |
| '-'       | 实线    |
| ':'       | 虚线    |
| '–'       | 破折线   |
| 'None','' | 什么都不画 |
| '-.'      | 点划线   |

## masker 标记形状

| 参数        | 描述       |
| --------- | -------- |
| 'o'       | 圆圈       |
| '.'       | 点        |
| 'D'       | 菱形       |
| 's'       | 正方形      |
| 'h'       | 六边形1     |
| '\*'      | 星号       |
| 'H'       | 六边形2     |
| 'd'       | 小菱形      |
| '\_'      | 水平线      |
| 'v'       | 一角朝下的三角形 |
| '8'       | 八边形      |
| '<'       | 一角朝左的三角形 |
| 'p'       | 五边形      |
| '>'       | 一角朝右的三角形 |
| ','       | 像素       |
| '^'       | 一角朝上的三角形 |
| '+'       | 加号       |
| ''        | 竖线       |
| 'None','' | 无        |
| 'x’       | X        |

## color或c 颜色

| 参数  | 颜色  |
| --- | --- |
| 'b' | 蓝色  |
| 'g' | 绿色  |
| 'r' | 红色  |
| 'y' | 黄色  |
| 'c' | 青色  |
| 'k' | 黑色  |
| 'm' | 洋红色 |
| 'w' | 白色  |

## 标题和x/y轴的标签

通过plt.title()或者ax.set\_title()函数可以设置相应图标的标题。

通过plt.xlabel()/plt.ylabel()或者ax.set\_xlabel()/ax.set\_ylabel()可以设置对应坐标轴的标签。

注意：**ax用来指代axes对象**。

## grid() 网格显示

```python
grid(b=None, which='major', axis='both', **kwargs)
```

参数说明：

* b：设置是否打开网格
* color：设置网格颜色
* linestyle：设置网格线型
* linewidth：设置网格线宽

## legend() 图例显示

```python
legend(*args, **kwargs)
```

参数说明：

* handles：添加到图例中的绘图对象(可省略)
* labels：对应于handles对象顺序的label，可省略(此时需要在画图时通过label参数指定每个图形对象的名称)
* ncol：图例的列数，可以通过该参数使得图例分列显示
* loc：图例设置的位置

| location string | location code |
| --------------- | ------------- |
| 'best'          | 0             |
| 'upper right'   | 1             |
| 'upper left'    | 2             |
| 'lower left'    | 3             |
| 'lower right'   | 4             |
| 'right'         | 5             |
| 'center left'   | 6             |
| 'cevter right'  | 7             |
| 'lower center'  | 8             |
| 'upper center'  | 9             |
| 'center'        | 10            |

## 坐标轴

通过plt.axis(\[xmin,xmax,ymin,ymax])可以设置坐标轴的范围，其中xmin,xmax,ymin,ymax分别表示x轴左边界，x轴右边界，y轴下边界，y轴上边界。

通过plt.xlim(xmin,xmax)和plt.ylim(ymin,ymax)方法可以分别调整x轴和y轴的范围，使用该函数时可以传参\[minval,maxval]来同时设置某轴的最小值和最大值，也可以分别通过xmin，xmax，ymin，ymax来单独设置某个轴的某个边界值。

```python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1,10,50)
y1,y2,y3,y4 = x / 2, np.sqrt(x), np.log(x), x**1.5 

plt.rcParams['axes.unicode_minus']=False  # 用来正常显示负号

#plt直接绘图
#同时修改xy坐标轴范围
plt.subplot(221)
plt.plot(x,y1)
plt.axis([-10,10,0,100])
#只修改x坐标轴范围
plt.subplot(222)
plt.plot(x,y2)
plt.xlim(-10,10)
#只修改y坐标轴范围
plt.subplot(223)
plt.plot(x,y3)
plt.ylim(0,100)
#只修改x坐标轴左边界
plt.subplot(224)
plt.plot(x,y4)
plt.xlim(xmin=-10)

plt.show()

#面向对象方式绘图
fig = plt.figure() #创建figure对象
ax1 = fig.add_subplot(221)
ax1.plot(x,y1)
ax1.axis([-10,10,0,100])

ax2 = fig.add_subplot(222)
ax2.plot(x,y2)
ax2.set_xlim(-10,10)

ax3 = fig.add_subplot(223)
ax3.plot(x,y3)
ax3.set_ylim(0,100)

ax4 = fig.add_subplot(224)
ax4.plot(x,y4)
ax4.set_xlim(xmin=-10)
plt.show()
```

## locator\_params() 坐标轴刻度的调整

通过locator\_params()方法来调整坐标轴的刻度间距，该函数的声明为：

```python
locator_params(axis='both', tight=None, **kwargs)
```

参数说明：

* axis：用来选择要调整的坐标轴，该参数有三个值'both','x','y'
* nbins：坐标轴划分的等份数

```python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1,50,20)
y = 2*x

fig = plt.figure() #创建figure对象
ax1 = fig.add_subplot(121)
ax1.plot(x,y)
ax1.locator_params(axis='x',nbins=20)

ax2 = fig.add_subplot(122)
ax2.plot(x,y)
ax2.locator_params(axis='y',nbins=20)

plt.show()
```

## 注释的添加

通过使用annotate()方法可以往图形上添加带箭头的注释，该函数的声明为：

```python
annotate(s, xy, *args, **kwargs)
```

参数说明：

* s：注释字符串
* xy：要注释的点
* xytext：放置注释字符串的位置
* arrowprops：设置在位置xy和xytext之间绘制的箭头的属性，参数类型为字典，其中常用的参数包括

| 参数        | 含义    |
| --------- | ----- |
| width     | 箭身的宽度 |
| headwidth | 箭头的宽度 |
| facecolor | 箭头的颜色 |

```python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1,50,20)
y = 2*x

fig = plt.figure() #创建figure对象
ax = fig.add_axes([0.1,0.1,0.8,0.8]) #添加坐标轴对象
ax.plot(x,y)
ax.annotate("(2,4)",xy=(2,4),xytext=(2,25),arrowprops={"facecolor":'r'})
plt.show()
```

通过使用text()方法可以往图形上只添加文字注释，该函数的声明为：

```python
text(x, y, s, fontdict=None, withdash=False, **kwargs)
```

参数说明：

* x,y：文字注释内容的x坐标和y坐标
* s：文字注释的内容
* fontfamily：文字字体类型，常用的包括'serif','sans-serif','cursive','fantasy','monospace'
* fontstyle：字体样式，常用的包括'normal','italic','oblique'
* fontsize/size：字体大小，可以采用数字
* fontweight/weight：设置字体的粗细，可以使用0\~1000范围内的数字来设置，数字越大字体越粗

注意：上述函数可以输出数学公式，使用方式和输出文本的用法一致，只需要设置s = r"mathexperssion"即可，其中mathexpression是包含在$$之间的字符串(常用的数学符号编写)。

```python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1,50,20)
y = np.sqrt(x)

fig = plt.figure() #创建figure对象
ax = fig.add_axes([0.1,0.1,0.8,0.8]) #添加坐标轴对象
ax.plot(x,y)
ax.text(15,5,r"$y=\sqrt{x}$",size=20,fontstyle="italic")
plt.show()
```

## 多图显示

通过plt.subplot()方法可以将figure划分为多个子图，但每条subplot命令只会创建一个子图，该函数的常用使用形式为：

```python
subplot(nrows, ncols, index, **kwargs)
```

参数说明：

* nrows：figure划分的行数
* ncols：figure划分的列数
* index：图案nrows行ncols列划分的块再按从左往右，从上往下的顺序排列的当前图的索引

```python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1,20,20)
y1,y2,y3 = np.sqrt(x),np.log(x),x**1.5

plt.subplot(131)
plt.plot(x,y1)
plt.subplot(132)
plt.plot(x,y2)
plt.subplot(133)
plt.plot(x,y3)

plt.show()
```

通过plt.subplots()方法可以创建一个figure和一批子图，返回的形式为(figure, subplots)，该方法的常用形式为：

```python
subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw) -> tuple
```

参数说明：

* nrows：figure划分的行数
* ncols：figure划分的列数

在使用该方式时，我们可以通过二维索引来获取子图，例如axes\[1,1]表示获取到的是第2行第2列的子图对象，然后利用该子图对象我们可以调用画图函数来进行图形绘制，当然也可以通过for循环来获取子图对象。

```python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1,20,20)
y1,y2,y3,y4 = np.sqrt(x),np.log(x),x**1.5,2*x + 2

ys = [y1,y2,y3,y4]
fig,axs = plt.subplots(2,2)
for y,ax in zip(ys,axs.flatten()):#使用for循环时需要展平返回的多维数组
    ax.plot(x,y)

plt.show()
```

### 面向对象的方式

对于面向对象的方式，首先需要新建一个figure对象，然后可以利用add\_subplot()函数新建坐标轴对象(该函数的参数和plt.subplot()类似)，再调用该函数即可进行绘图，示例代码如下：

```python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(1,20,20)
y1,y2 = np.sqrt(x),np.log(x)

fig = plt.figure()
ax1 = fig.add_subplot(1,2,1)
ax1.plot(x,y1)
ax2= fig.add_subplot(1,2,2)
ax2.plot(x,y2)
plt.show()
```

## 图片显示

matplotlib也可以用来展示图片，而且它可以向展示上述的绘制图形一样同时展示多张图片，通过plt.imshow(X)可以用来显示图片，其中X可以是通过PLI.Image.open()或cv2.imread()或matplotlib.image.imread()打开的图形数据，示例代码如下：

```python
import matplotlib.pyplot as plt
import cv2

imgs = []
for i in range(1,5):
    imgs.append(cv2.imread(str(i) + ".jpg"))
plt.figure(figsize=[4,6])
i = 1
for img in imgs:
    plt.subplot(4,2,i)
    plt.imshow(img)
    i += 1
    #cv2打开图片是按BGR，而matplotlib是按RGB显示因此当使用cv2打开图片是需要先将图片转换为RGB
    img_c = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
    plt.subplot(4,2,i)
    plt.imshow(img_c)
    i += 1
plt.show()
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lujw666.gitbook.io/learn/python/03-import/matplotlib/04-can-shu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
