matplotlib基本功能
matplotlib概述
matplotlib是python的一个绘图库。使用它可以很方便的绘制出版质量级别的图形。
matplotlib基本功能
基本绘图
绘图核心API
import numpy as np
import matplotlib.pyplot as mp
# xarray: <序列> 水平坐标序列
# yarray: <序列> 垂直坐标序列
mp.plot(xarray, yarray)
#显示图表
mp.show()
绘制水平线与垂直线:
import numpy as np
import matplotlib.pyplot as mp
# vertical 绘制垂直线
mp.vlines(vval, ymin, ymax, ...)
# horizotal 绘制水平线
mp.hlines(xval, xmin, xmax, ...)
#显示图表
mp.show()
举个例子
import numpy as np
import matplotlib.pyplot as mp
x = np.array([0, 1, 2, 3, 4, 5, 6, 7])
y = np.array([45,81,36,51,19,92,23,51])
mp.plot(x, y)
# 绘制水平线 在纵坐标为60的地方,画一条横坐标从1到6.5的水平线
mp.hlines(60, 1, 6.5)
# 绘制垂直线
mp.vlines([1,2,3,4,5], [10,20,30,40,50], [25,35,45,55,65])
#分别在横坐标为1 2 3 4 5的地方,画5条垂直线,具体起始坐标是后面两个列表的元素
mp.show()
运行结果:
线型、线宽和颜色
linestyle: 线型 ‘-’ ‘–’ ‘-.’ ‘:’
linewidth: 线宽(数字)
color: <关键字参数> 颜色,可以写:英文颜色单词 或 常见颜色英文单词首字母 或 #495434 或 (1,1,1) 或 (1,1,1,1)
alpha: <关键字参数> 透明度(浮点数值)
mp.plot(xarray, yarray, linestyle='', linewidth=1, color='', alpha=0.5)
设置坐标轴范围
x_limt_min: x轴范围最小值
x_limit_max: x轴范围最大值
y_limt_min: y轴范围最小值
y_limit_max: y轴范围最大值
mp.xlim(x_limt_min, x_limit_max)
mp.ylim(y_limt_min, y_limit_max)
设置坐标刻度
x_val_list: x轴刻度值序列
x_text_list: x轴刻度标签文本序列 [可选]
y_val_list: y轴刻度值序列
y_text_list: y轴刻度标签文本序列 [可选]
mp.xticks(x_val_list , x_text_list )
mp.yticks(y_val_list , y_text_list )
刻度文本的特殊语法 – LaTex排版语法字符串
r'$x^n+y^n=z^n$', r'$\int\frac{1}{x} dx = \ln |x| + C$', r'$-\frac{\pi}{2}$'
x 2 + y 2 = z 2 , ∫ 1 x d x = ln ∣ x ∣ + C , − π 2 x^2+y^2=z^2, \int\frac{1}{x} dx = \ln |x| + C, -\frac{\pi}{2} x2+y2=z2,∫x1dx=ln∣x∣+C,−2π
设置坐标轴
坐标轴名:left / right / bottom / top
# 获取当前坐标轴字典,{'left':左轴,'right':右轴,'bottom':下轴,'top':上轴 }
ax = mp.gca() # getCurrentaxis
# 获取其中某个坐标轴
axis = ax.spines['坐标轴名']
# 设置坐标轴的位置。 该方法需要传入2个元素的元组作为参数
# type: <str> 移动坐标轴的参照类型 一般为'data' (以数据的值作为移动参照值)
# val: 参照值
axis.set_position(('data', val))
# 设置坐标轴的颜色
# color: <str> 颜色值字符串
axis.set_color(color)
举个例子:
#设置坐标轴
ax = mp.gca()
axis_b = ax.spines['bottom']
axis_b.set_position(('data', 0))
axis_l = ax.spines['left']
axis_l.set_position(('data', 0.5))
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
运行结果:
图例
再绘制曲线时定义曲线的label(plot函数中的参数)
label: <关键字参数 str> 支持LaTex排版语法字符串
设置图例的位置
loc: <关键字参数> 制定图例的显示位置 (若不设置loc,则显示默认位置)
String Code
‘best’ 0
‘upper right’ 1
‘upper left’ 2
‘lower left’ 3
‘lower right’ 4
‘right’ 5
‘center left’ 6
‘center right’ 7
‘lower center’ 8
‘upper center’ 9
‘center’ 10
mp.plot(xarray, yarray ... label='', ...)
mp.legend(loc='')
特殊点
xarray: <序列> 所有需要标注点的水平坐标组成的序列
yarray: <序列> 所有需要标注点的垂直坐标组成的序列
mp.scatter(xarray, yarray,
marker='', #点型 ~ matplotlib.markers
s=70, #大小
edgecolor='', #边缘色
facecolor='', #填充色
zorder=3 #绘制图层编号 (编号越大,图层越靠上)
)
marker点型可参照:help(matplotlib.markers)
备注
案例:为在某条曲线上的点添加备注,指明函数方程与值。
# 在图表中为某个点添加备注。包含备注文本,备注箭头等图像的设置。
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字典参数的常用key
arrowprops=dict(
arrowstyle='', #定义箭头样式
connectionstyle='' #定义连接线的样式
)
箭头样式(arrowstyle)字符串如下
=============================================
Name Attrs
=============================================
'-' 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
=============================================
连接线样式(connectionstyle)字符串如下
=============================================
Name Attrs
=============================================
'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
=============================================
举个例子:(绘制 sin(x) 和 cos(x) / 2 函数)
import numpy as np
import matplotlib.pyplot as mp
#从-pi到pi拆1000个点
x = np.linspace(-np.pi, np.pi, 1000)
sinx = np.sin(x)
# 画一个y = cos(x)/2
cosx = np.cos(x) / 2
# 修改x轴的刻度
vals = [-np.pi, -np.pi/2, 0, np.pi/2, np.pi]
texts = [r'$-\pi$', r'$-\frac{\pi}{2}$', '0',
r'$\frac{\pi}{2}$', r'$\pi$']
mp.xticks(vals, texts) #设置x轴坐标刻度
# 设置坐标轴
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.yticks([-1.0, -0.5, 0.5, 1.0]) #设置y轴刻度
#设置绘制的两条线的属性
mp.plot(x, sinx, linestyle='-.', linewidth=2,
color='dodgerblue', alpha=0.8,
label=r'$y = sin(x)$')
mp.plot(x, cosx, linestyle='--', linewidth=2,
color='orangered', alpha=0.8,
label=r'$y = \frac{1}{2}cos(x)$')
# 绘制特殊点
mp.scatter([np.pi/2, np.pi/2], [1, 0],
s=[120,80], marker='o', edgecolor='red',
facecolor='green', zorder=3) #zorder是图层顺序
# 为特殊点添加备注
mp.annotate(r'$[\frac{\pi}{2}, 1]$',
xycoords='data', xy=(np.pi/2