## matplotlib概述

matplotlib是python的一个绘图库。使用它可以很方便的绘制质量级别高的图形。

## matplotlib基本绘图

### 先来几个案例简单了解一下matplotlib

#### 案例1(绘制一条余弦曲线)

• 语法
import numpy as npimport matplotlib.pyplot as mp# xarray: <序列> 水平坐标序列# yarray: <序列> 垂直坐标序列mp.plot(xarray, yarray)#显示图表mp.show()

import numpy as npimport matplotlib.pyplot as mp#生成一条正弦曲线x = np.linspace(-np.pi, np.pi, 1000)print(x.shape)sin_x = np.sin(x)#绘制mp.plot(x, sin_x)mp.show()

#### 案例2(绘制水平线与垂直线)

• 语法
import numpy as npimport matplotlib.pyplot as mp# vertical 绘制垂直线mp.vlines(vval, ymin, ymax, ...)#vval为x坐标值,ymin和ymax为垂直线的最小最大值# horizotal 绘制水平线mp.hlines(xval, xmin, xmax, ...)#xval为y坐标值, xmin和xmax为水平线的最小最大值#显示图表mp.show()

import numpy as npimport matplotlib.pyplot as mpxs = np.arange(6)ys = np.array([20, 60, 40, 50, 10, 20])mp.plot(xs, ys)mp.vlines(3, 20, 50)mp.hlines(30, 1, 4)mp.show()

#### 案例3(绘制多条垂直/水平线)

import numpy as npimport matplotlib.pyplot as mpxs = np.arange(6)ys = np.array([20, 60, 40, 50, 10, 20])mp.plot(xs, ys)mp.vlines([3, 5, 7], 20, 50)mp.hlines(30, 1, 4)mp.show()

### 线型、线宽和颜色

• 语法
mp.plot(xarray, yarray, linestyle='', linewidth=1, color='', alpha=0.5)

 参数 含义 参数值 linestyle 线型 ​​"-"​​​ ​​"--"​​​ ​​":"​​​ ​​".-"​​ linewidth 线宽 数字 color 颜色 颜色的英文单词 / 常见颜色英文单词首字母 / ​​#495434​​​ / ​​(1,1,1)​​​ / ​​(1,1,1,1)​​ alpha 透明度 浮点数值

• 举个例子

import numpy as npimport matplotlib.pyplot as mpx = np.linspace(-np.pi, np.pi, 1000)sin_x = np.sin(x)cos_x = np.cos(x)mp.plot(x, sin_x, linestyle=':', alpha = 0.8,        linewidth= 2, color='dodgerblue')mp.plot(x, cos_x, linestyle='-.', alpha = 0.8,        linewidth= 2, color='orangered')mp.show()

### 设置坐标轴范围

• 语法
mp.xlim(x_limt_min, x_limit_max)#x_limt_min:    <float> x轴范围最小值#x_limit_max:   <float> x轴范围最大值mp.ylim(y_limt_min, y_limit_max)#y_limt_min:    <float> y轴范围最小值#y_limit_max:   <float> y轴范围最大值
• 举个例子(设置坐标轴范围)

import numpy as npimport matplotlib.pyplot as mpx = np.linspace(-np.pi, np.pi, 1000)sin_x = np.sin(x)cos_x = np.cos(x)mp.plot(x, sin_x, linestyle=':', alpha = 0.8,        linewidth= 2, color='dodgerblue')mp.plot(x, cos_x, linestyle='-.', alpha = 0.8,        linewidth= 2, color='orangered')mp.xlim(0, np.pi)mp.ylim(0, 1)mp.show()

### 设置坐标刻度

• 语法
mp.xticks(x_val_list, x_text_list)#x_val_list:    x轴刻度值序列#x_text_list:   x轴刻度标签文本序列 [可选]mp.yticks(y_val_list, y_text_list)#y_val_list:    y轴刻度值序列#y_text_list:   y轴刻度标签文本序列 [可选]

#### 举个例子(修改坐标轴刻度)

import numpy as npimport matplotlib.pyplot as mpx = np.linspace(-np.pi, np.pi, 1000)sin_x = np.sin(x)cos_x = np.cos(x)mp.plot(x, sin_x, linestyle=':', alpha = 0.8,        linewidth= 2, color='dodgerblue')mp.plot(x, cos_x, linestyle='-.', alpha = 0.8,        linewidth= 2, color='orangered')mp.xticks([-np.pi, 0, np.pi],          ['-π', '0', 'π'])mp.show()

#### 举个例子2(Latex排版语法字符串)

import numpy as npimport matplotlib.pyplot as mpx = np.linspace(-np.pi, np.pi, 1000)sin_x = np.sin(x)cos_x = np.cos(x)mp.plot(x, sin_x, linestyle=':', alpha = 0.8,        linewidth= 2, color='dodgerblue')mp.plot(x, cos_x, linestyle='-.', alpha = 0.8,        linewidth= 2, color='orangered')mp.xticks(    [-np.pi, -np.pi / 2, 0, np.pi / 2, np.pi],    [r'$-\pi$', r'$-\frac{\pi}{2}$', '0',     r'$\frac{\pi}{2}$', r'$\pi$'])mp.yticks([-1.0, -0.5, 0, 0.5, 1])mp.show()

### 设置坐标轴

• 语法
# 获取当前坐标轴字典，{'left':左轴,'right':右轴,'bottom':下轴,'top':上轴 }ax = mp.gca()# 获取其中某个坐标轴axis = ax.spines['坐标轴名']#坐标轴名：left/right/bottom/top# 设置坐标轴的位置。 该方法需要传入2个元素的元组作为参数axis.set_position((type, val))# type: <str> 移动坐标轴的参照类型  一般设置为'data' (以数据的值作为移动参照值)# val:  参照值# 设置坐标轴的颜色axis.set_color(color)# color: <str> 颜色值字符串#若需要隐藏掉坐标轴，则可设置为color参数为'none'
• 举个例子

import numpy as npimport matplotlib.pyplot as mpx = np.linspace(-np.pi, np.pi, 1000)sin_x = np.sin(x)cos_x = np.cos(x)mp.plot(x, sin_x, linestyle=':', alpha = 0.8,        linewidth= 2, color='dodgerblue')mp.plot(x, cos_x, linestyle='-.', alpha = 0.8,        linewidth= 2, color='orangered')# 设置坐标轴ax = mp.gca()ax.spines['top'].set_color('none')ax.spines['right'].set_color('none')ax.spines['left'].set_position(('data', 0))ax.spines['bottom'].set_position(('data', 0))mp.show()

### 图例

• 语法
mp.legend(loc = 0)

• 举个例子

import numpy as npimport matplotlib.pyplot as mpx = np.linspace(-np.pi, np.pi, 1000)sin_x = np.sin(x)cos_x = np.cos(x)mp.plot(x, sin_x, linestyle=':', alpha = 0.8,        linewidth= 2, color='dodgerblue',         label = r'sin(x)')mp.plot(x, cos_x, linestyle='-.', alpha = 0.8,        linewidth= 2, color='orangered',        label = r'cos(x)')mp.legend(loc = 2)mp.show()

### 特殊点

• 语法
# xarray: <序列> 所有需要标注点的水平坐标组成的序列# yarray: <序列> 所有需要标注点的垂直坐标组成的序列mp.scatter(xarray, yarray,            marker='',       #点型 ~ matplotlib.markers           s='',            #大小           edgecolor='',    #边缘色           facecolor='',    #填充色           zorder=3)            #绘制图层编号 （编号越大，图层越靠上,就会把图层较小的图层覆盖掉）

• 举个例子

# 绘制特殊点px = [3 / 4 * np.pi, 3 / 4 * np.pi]py = [np.sin(px[0]), np.cos(px[1])]mp.scatter(px, py, marker='o', color='red',           s=70, label='Points', zorder=3)

### 备注

• 语法
# 在图表中为某个点添加备注。包含备注文本，备注箭头等图像的设置。mp.annotate(    r'$\frac{\pi}{2}$',         #备注中显示的文本内容    xycoords='data',            #备注目标点所使用的坐标系（data表示数据坐标系）    xy=(x, y),                  #备注目标点的坐标    textcoords='offset points', #备注文本所使用的坐标系（offset points表示参照点的偏移坐标系）    xytext=(x, y),              #备注文本的坐标    fontsize=14,                #备注文本的字体大小    arrowprops=dict()           #使用字典定义文本指向目标点的箭头样式)

arrowprops参数使用字典定义指向目标点的箭头样式：

#arrowprops字典参数的常用keyarrowprops=dict(    arrowstyle='',      #定义箭头样式    connectionstyle=''  #定义连接线的样式)

 ​​'-'​​ None ​​'->'​​ head_length=0.4,head_width=0.2 ​​'-['​​ widthB=1.0,lengthB=0.2,angleB=None ​​'|-|'​​ widthA=1.0,widthB=1.0 ​​'-|>'​​ head_length=0.4,head_width=0.2 ​​'<-'​​ head_length=0.4,head_width=0.2 ​​'<->'​​ head_length=0.4,head_width=0.2 ​​'<|-'​​ head_length=0.4,head_width=0.2 ​​'<|-|>'​​ head_length=0.4,head_width=0.2 ​​'fancy'​​ head_length=0.4,head_width=0.4,tail_width=0.4 ​​'simple'​​ head_length=0.5,head_width=0.5,tail_width=0.2 ​​'wedge'​​ tail_width=0.3,shrink_factor=0.5

 ‘angle’ angleA=90,angleB=0,rad=0.0 ‘angle3’ angleA=90,angleB=0 ‘arc’ angleA=0,angleB=0,armA=None,armB=None,rad=0.0 ‘arc3’ rad=0.0 ‘bar’ armA=0.0,armB=0.0,fraction=0.3,angle=None
• 举个例子

mp.annotate(    r'$[\frac{3\pi}{4}, cos(\frac{3\pi}{4})]$',    xycoords='data',    xy=(3/4 * np.pi, np.cos(px[1])),    textcoords='offset points',    xytext=(-80, -30),    fontsize=14,    arrowprops=dict(        arrowstyle='-|>',        connectionstyle='angle3'    ))`

￼￼