Matlpotlib学习
- Matplotlib 是一个非常强大的 Python 画图工具。可以画线图、散点图、等高线图、条形图、柱状图、3D图像、动画图形等。
一、基本使用
1.1 基本用法
- 流程
(1). 定义一个窗口,matplotlib.pyplot.figure
(2). 绘制曲线
(3). 显示图像,matplotlib.pyplot.show
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 50)
y = 2*x + 1
plt.figure()
plt.plot(x, y)
plt.show()
1.2 figure图像
- matplotlib 的 figure 就是一个 单独的 figure 小窗口, 小窗口里面还可以有更多的小图片。
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
plt.figure(num=3, figsize=(8, 5)) #num设置窗口编号,figsize设置窗口大小
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--') #linewidth:线宽,linestyle:线的风格
plt.show()
1.3 设置坐标轴
- matplotlib.pyplot.xlabel:设置x坐标轴名称
- matplotlib.pyplot.ylabel:设置y坐标轴名称
- matplotlib.pyplot.xlim:设置x坐标轴范围
- matplotlib.pyplot.ylim:设置y坐标轴范围
- matplotlib.pyplot.xticks:设置x轴刻度
- matplotlib.pyplot.yticks:设置y轴刻度以
- matplotlib.pyplot.gca:获取当前坐标轴信息
- matplotlib.pyplot..spines:设置边框
- .xaxis.set_ticks_position:设置x坐标刻度数字或名称的位置,默认bottom.(所有位置:top,bottom,both,default,none)
- .yaxis.set_ticks_position:设置y坐标刻度数字或名称的位置,默认left.(所有位置:left,right,both,default,none)
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')
new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.show()
*使用plt.yticks设置y轴刻度以及名称:刻度为[-2, -1.8, -1, 1.22, 3];对应刻度的名称为[‘really bad’,’bad’,’normal’,’good’, ‘really good’].
*plt.yticks([-2, -1.8, -1, 1.22, 3],[r'', r'', r'', r'', r'']),两个$符号种的字母的字体会改变,两个$中空格显示不出来,需要用转置符\.
1.4 Legend图例
- matplotlib 中的 legend 图例就是为了帮我们展示出每个数据对应的图像名称. 更好的让读者认识到你的数据结构。
- 使用legend需要对窗中的每个图设置lable。如果不用自己的lable需要使用handles这个参数
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2
plt.figure()
#set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))
# set new sticks
new_sticks = np.linspace(-1, 2, 5)
plt.xticks(new_sticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
# set line syles
l1, = plt.plot(x, y1, label='linear line') #l1, l2,要以逗号结尾, 因为plt.plot() 返回的是一个列表
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
plt.legend(loc='upper right')#参数 loc='upper right' 表示图例将添加在图中的右上角
plt.legend(handles=[l1, l2], labels=['up', 'down'], loc='best')
put.show()
loc的可选值:
'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,
1.5 Annotation标注
*annotate参数说明:
调用签名:plt.annotate(string, xy=(np.pi/2, 1.0), xytext=((np.pi/2)+0.15, 1,5), weight="bold", color="b", arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color="b"))
- string:图形内容的注释文本
- xy:被注释图形内容的位置坐标
- xytext:注释文本的位置坐标
- weight:注释文本的字体粗细风格
- color:注释文本的字体颜色
- arrowprops:指示被注释内容的箭头的属性字典
matploylib.pylot.text()也可以添加注释
调用签名:
ext(x,y,string,fontsize=15,verticalalignment="top",horizontalalignment="right")
- x,y:表示坐标值上的值
- string:表示说明文字
- fontsize:表示字体大小
- verticalalignment:垂直对齐方式 ,参数:[ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]
- horizontalalignment:水平对齐方式 ,参数:[ ‘center’ | ‘right’ | ‘left’ ]
x = np.linspace(-3, 3, 50)
y = 2*x + 1
plt.figure(num=1, figsize=(8, 5),)
plt.plot(x, y)
#移动坐标
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
#画虚线和点
x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
# set dot styles
plt.scatter([x0, ], [y0, ], s=50, color='b')
#添加注释annotate
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2")) #xycoords='data' 是说基于数据的值来选位置
#添加注释text
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
fontdict={'size': 16, 'color': 'r'})
1.6 tick能见度
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = 0.1*x
plt.figure()
# 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
plt.plot(x, y, linewidth=10, zorder=1)
plt.ylim(-2, 2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
#调整能见度
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
# 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2))
plt.show()
二、画图种类
(1)散点图
函数原型:matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, *, data=None, **kwargs)
参数解释:
- x,y:表示的是大小为(n,)的数组,也就是我们即将绘制散点图的数据点
- s:是一个实数或者是一个数组大小为(n,),这个是一个可选的参数。
- c:表示的是颜色,也是一个可选项。默认是蓝色'b',表示的是标记的颜色,或者可以是一个表示颜色的字符,或者是一个长度为n的表示颜色的序列等等,感觉还没用到过现在不解释了。但是c不可以是一个单独的RGB数字,也不可以是一个RGBA的序列。可以是他们的2维数组(只有一行)。
- marker:表示的是标记的样式,默认的是'o'。
- cmap:Colormap实体或者是一个colormap的名字,cmap仅仅当c是一个浮点数数组的时候才使用。如果没有申明就是image.cmap
- norm:Normalize实体来将数据亮度转化到0-1之间,也是只有c是一个浮点数的数组的时候才使用。如果没有申明,就是默认为colors.Normalize。
- vmin,vmax:实数,当norm存在的时候忽略。用来进行亮度数据的归一化。
- alpha:实数,0-1之间。
import matplotlib.pyplot as plt
import numpy as np
n = 1024 # data size
X = np.random.normal(0, 1, n) # 每一个点的X值
Y = np.random.normal(0, 1, n) # 每一个点的Y值
T = np.arctan2(Y,X) # for color value
plt.scatter(X, Y, s=75, c=T, alpha=.5)
plt.xlim(-1.5, 1.5)
plt.xticks(()) # ignore xticks
plt.ylim(-1.5, 1.5)
plt.yticks(()) # ignore yticks
plt.show()
(2)柱状图
函数原型:bar(x, height, width=0.8, bottom=None, , align='center', data=None, kwargs*)
参数说明:
参数 | 说明 | 类型 |
---|---|---|
x | x坐标 | int,float |
height | 条形的高度 | int,float |
width | 宽度 | 0~1,默认0.8 |
botton | 条形的起始位置 | 也是y轴的起始坐标 |
align | 条形的中心位置 | “center”,"lege"边缘 |
color | 条形的颜色 | “r","b","g","#123465",默认“b" |
edgecolor | 边框的颜色 | 同上 |
linewidth | 边框的宽度 | 像素,默认无,int |
tick_label | 下标的标签 | 可以是元组类型的字符组合 |
log | y轴使用科学计算法表示 | bool |
orientation | 是竖直条还是水平条 | 竖直:"vertical",水平条:"horizontal" |
import matplotlib.pyplot as plt
import numpy as np
n = 12
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
plt.bar(X, +Y1)
plt.bar(X, -Y2)
plt.xlim(-.5, n)
plt.xticks(())
plt.ylim(-1.25, 1.25)
plt.yticks(())
#加颜色
plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
#加数据
for x, y in zip(X, Y1):
# ha: horizontal alignment
# va: vertical alignment
plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom')
for x, y in zip(X, Y2):
# ha: horizontal alignment
# va: vertical alignment
plt.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va='top')
plt.show()
(3)等高线图
函数原型:contour([X, Y,] Z, [levels], **kwargs)
,具体见官方文档
import matplotlib.pyplot as plt
import numpy as np
def f(x,y):
# the height function
return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 -y**2)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X,Y = np.meshgrid(x, y) #定义网格
#使用函数plt.contourf把颜色加进去
# use plt.contourf to filling contours
# X, Y and value for (X,Y) point
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)
#使用plt.contour函数划线
# use plt.contour to add contour lines
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
#添加高度数字
plt.clabel(C, inline=True, fontsize=10)
plt.xticks(())
plt.yticks(())
plt.show
(4)image图片
*随即矩阵画图,这里我们打印出的是纯粹的数字,而非自然图像。
import matplotlib.pyplot as plt
import numpy as np
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
#添加colorbar
plt.colorbar(shrink=.92)
plt.xticks(())
plt.yticks(())
plt.show()
interpolation的取直参见官方网站
(5)3D数据
- 首先要从mpl_toolkits.mplot3d导入Axes3D
- 然后ax = Axes3D(fig)
- 使用ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))绘图
- 使用ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))画投影
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
# X, Y value
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y) # x-y 平面的网格
R = np.sqrt(X ** 2 + Y ** 2)
# height value
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
#投影
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))
ax.set_zlim(-2,2)
put.show()
三、多图合并显示
3.1 subplot多合一显示
- 均匀图中图
import matplotlib.pyplot as plt
plt.subplot(2,2,1)
plt.plot([0,1],[0,1])
plt.subplot(2,2,2)
plt.plot([0,1],[0,2])
plt.subplot(223)
plt.plot([0,1],[0,3])
plt.subplot(224)
plt.plot([0,1],[0,4])
plt.figure()
- 不均匀图中图
import matplotlib.pyplot as plt
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])
plt.subplot(2,3,4)
plt.plot([0,1],[0,2])
plt.subplot(235)
plt.plot([0,1],[0,3])
plt.subplot(236)
plt.plot([0,1],[0,4])
plt.figure()
3.2 subplot分格显示
- 方法一:subplot2grid
- 方法二:gridspec
- 方法三:subplots
#method 1:subplot2grid
import matplotlib.pyplot as plt
plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)#colspan=3表示列的跨度为3, rowspan=1表示行的跨度为1。默认值都为1.
ax1.plot([1, 2], [1, 2]) # 画小图
ax1.set_title('ax1_title') # 设置小图的标题
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))
ax4.scatter([1, 2], [2, 2])
ax4.set_xlabel('ax4_x')
ax4.set_ylabel('ax4_y')
plt.show()
#method 2:gridspec
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.figure()
gs = gridspec.GridSpec(3, 3) #将整个图像窗口分成3行3列
ax6 = plt.subplot(gs[0, :])
ax7 = plt.subplot(gs[1, :2])
ax8 = plt.subplot(gs[1:, 2])
ax9 = plt.subplot(gs[-1, 0])
ax10 = plt.subplot(gs[-1, -2])
###method 3:subplots
f, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1,2], [1,2])
plt.tight_layout()
plt.show()
3.3 图中图
# 导入pyplot模块
import matplotlib.pyplot as plt
# 初始化figure
fig = plt.figure()
# 创建数据
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
#大图
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8 #首先确定大图左下角的位置以及宽高,注意,4个值都是占整个figure坐标系的百分比
#将大图坐标系添加到figure中,颜色为r(red),取名为title
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
#小图:步骤和绘制大图一样,注意坐标系位置和大小的改变
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')
#采用一种更简单方法画小图,即直接往plt里添加新的坐标系
plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1], x, 'g') # 注意对y进行了逆序处理
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')
plt.show()
3.4 次坐标轴
#第一个坐标轴
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 * y1
fig, ax1 = plt.subplots()
#第二个坐标轴
ax2 = ax1.twinx() #对ax1调用twinx()方法,生成如同镜面效果后的ax2
ax1.plot(x, y1, 'g-') # green, solid line
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.plot(x, y2, 'b-') # blue
ax2.set_ylabel('Y2 data', color='b')
plt.show()
四、动画
- 调用FuncAnimation函数生成动画。参数说明:
参数 描述 fig 进行动画绘制的figure func 自定义动画函数,即传入刚定义的函数animate frames 动画长度,一次循环包含的帧数 init_func 自定义开始帧,即传入刚定义的函数init interval 更新频率,以ms计 blit 选择更新所有点,还是仅更新产生变化的点。应选择True,但mac用户 请选择False,否则无法显示动画
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
#构造自定义动画函数animate,用来更新每一帧上各个x对应的y坐标值,参数表示第i帧
def animate(i):
line.set_ydata(np.sin(x + i/10.0))
return line,
def init():
line.set_ydata(np.sin(x ))
return line,
#构造开始帧函数init
ani = animation.FuncAnimation(fig=fig,
func=animate,
frames=100,
init_func=init,
interval=20,
blit=False)
plt.show()
网友评论