官方文档 :http://matplotlib.org/
完美主义者的配色方案:http://colorbrewer2.org/
学习网站:http://reverland.org/python/2012/09/07/matplotlib-tutorial/
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50) #50个-1到1之间的数
y1 = 3*x + 1
y2= x**2
plt.figure() #定义图像窗口
plt.plot(x, y1) #绘制图像
plt.show() #显示图像
plt.figure(num=3, figsize=(8, 5),) #窗口编号为3,大小为(8,5)
plt.plot(x, y2)
# 画在同一个figure里面
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--') #线的颜色、宽度、类型
plt.show()
# set x limits
plt.xlim((-1, 2)) #x轴范围
plt.ylim((-2, 3)) #y轴范围
plt.xlabel('I am x') #x的label
plt.ylabel('I am y') #y的label
# set new sticks
new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks) #x轴刻度
# set tick labels
#y轴刻度
plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
plt.show()
#设置边框
#获取当前坐标轴信息
ax = plt.gca()
ax.spines['right'].set_color('none') #.spines设置right侧边框,.set_color设置边框颜色:默认白色
ax.spines['top'].set_color('none')
#设置x坐标刻度数字或名称的位置
ax.xaxis.set_ticks_position('bottom') # position类型: [ 'top' | 'bottom' | 'both' | 'default' | 'none' ]
#.spines设置边框:x轴;.set_position设置边框位置:y=0的位置
ax.spines['bottom'].set_position(('data', 0))
# 属性1 'outward' | 'axes' | 'data'
# 属性2:axes: percentage of y axis
# 属性3:data: depend on y data
ax.yaxis.set_ticks_position('left')
# ACCEPTS: [ 'left' | 'right' | 'both' | 'default' | 'none' ]
ax.spines['left'].set_position(('data',0))
plt.show()
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,y1)
plt.xlim((-1,2))
plt.ylim((-2,3))
new_sticks = np.linspace(-1,2,5)
plt.xticks(new_sticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],
[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
l1, = plt.plot(x,y1,label='linear line')
l2, = plt.plot(x,y2,color ='red',linewidth =1.0,linestyle ='--',label ='square line')
plt.legend(loc ='upper right')
plt.legend(handles=[l1, l2], labels=['up', 'down'], loc='best') #调整位置和名称
plt.show()
注解:
1、需要注意的是 l1,
l2,
要以逗号结尾, 因为plt.plot()
返回的是一个列表.
2、其中’loc’参数有多种,’best’表示自动分配最佳位置,其余的如下:
'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,
import matplotlib.pyplot as plt
import numpy as np
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)
plt.scatter([x0, ], [y0, ], s=50, color='b')
# method 1:
#####################
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"))
# method 2:
########################
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
fontdict={'size': 16, 'color': 'r'})
plt.show()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = 0.1*x
plt.figure()
plt.plot(x, y, linewidth=10)
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)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7))
plt.show()
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D #3D
n1 = 1024
X1 = np.random.normal(0,1,n1)
Y1 = np.random.normal(0,1,n1)
T = np.arctan2(Y1,X1)
#---------------------------------Scatter-------------------------------------
plt.figure(1)
#输入X1和Y1作为location,size=75,颜色为T,color map用默认值,透明度alpha 为 50%
plt.scatter(X1,Y1,s=75,c=T,alpha= .5)
plt.xlim(-1.5,1.5)
#隐藏xticks
plt.xticks(())
plt.ylim(-1.5,1.5)
plt.yticks(())
plt.show()
#-------------------------------------bar--------------------------------------
n2 = 12
X2 = np.arange(n2)
Y2 = (1-X2/float(n2))*np.random.uniform(0.5,1.0,n2)
plt.figure(2)
plt.bar(X2,+Y2,facecolor = '#9999ff',edgecolor='white') #+Y1: up the xaxis,-Y1:down the xaxis
plt.xlim(-.5, n2)
plt.xticks(())
plt.ylim(-1.25, 1.25)
plt.yticks(())
for x,y in zip(X2 ,Y2):
#%.2f保留两位小数,横向居中对齐ha='center',纵向底部(顶部)对齐va='bottom':
plt.text(x+0.4,y+0.05,'%.2f' %y,ha='center',va='bottom')
plt.show()
#---------------------------------------contour-----------------------------------------
n3 = 256
x3 = np.linspace(-3,3,n3)
y3 = np.linspace(-3,3,n3)
X3,Y3 = np.meshgrid(x3,y3)
Z3 = (1-X3/2+X3**5+Y3**3)*np.exp(-X3**2-Y3**2)
#用contourf填充contour:透明度0.75,将z3的值对于到color map的暖色组中找对应颜色;等高线密集程度为8
plt.contourf(X3,Y3,Z3,8,alpha = .75,cmap = plt.cm.hot)
#添加等高线
C = plt.contour(X3,Y3,Z3,8 ,colors ='black',linewidth = .5)
#Label:inline控制是否将Label画在线里面
plt.clabel(C,inline = True,fontsize = 10)
plt.xticks()
plt.yticks()
plt.show()
#-------------------------------------------Image-----------------------------------------
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
#interpolation插值,origin=‘lower’->原点的位置
#http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower') #cmap=plt.cmap.bone
#colorbar:shrink->colorbar的长度变为原来的92%
plt.colorbar(shrink=.92)
plt.xticks(())
plt.yticks(())
plt.show()
#-------------------------------------------------3D------------------------------------
fig4 = plt.figure(4)
#在窗口上定义3D坐标
ax = Axes3D(fig4)
X4 = np.arange(-4,4,0.25)
Y4 =np.arange(-4,4,0.25)
#x-y平面的网络
X4,Y4 = np.meshgrid(X4,Y4)
#定义高度值
Z4 = np.sin(np.sqrt(X4**2+Y4**2))
#三维曲面:rstride:row的跨度;cstride:column的跨度;cmap选取颜色
ax.plot_surface(X4,Y4,Z4,rstride=1,cstride=1,cmap=plt.get_cmap('rainbow'))
#等高线:zdir->向z方向投影,
ax.contourf(X4,Y4,Z4,zdir='z',offset = -2,cmap=plt.get_cmap('rainbow'))
plt.show()
如图:
Scatter | Bar | Contour | Image | 3D |
![]() |
![]() |
![]() |
![]() |
![]() |
import matplotlib.pyplot as plt
plt.figure(1)
#2行1列当前位置为1
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])
#2行3列当前位置4
plt.subplot(234)
plt.plot([0,1],[0,3])
plt.show()
plt.figure(2)
#(3,3)窗口分成3行3列; (0,0):从第0行第0列开始作图,colspan=3:列的跨度为3. colspan和rowspan缺省, 默认跨度为1.
ax1 = plt.subplot2grid((3,3),(0,0),colspan=3)
ax1.plot([1,2],[1,2])
ax1.set_title('ax1_title')
ax2 = plt.subplot2grid((3,3),(1,0),rowspan=2)
ax2.scatter([1,2],[2,2])
ax2.set_xlabel('ax2_x')
ax2.set_ylabel('ax2_y')
plt.figure(3)
#窗口分成3行3列.
gs = gridspec.GridSpec(3,3)
#0行所有列
ax3 = plt.subplot(gs[0,:])
#倒数第1行,倒数第2列
ax4 = plt.subplot(gs[-1,-2])
#2行2列窗口,sharex=True:共享x轴坐标
#第1行从左至右依次放ax5和ax6, 第2行从左至右依次放ax7和ax8.
f5,((ax5,ax6),(ax7,ax8))=plt.subplots(2,2,sharex =True,sharey = True)
ax5.scatter([1,2],[1,2])
#紧凑显示图像
plt.tight_layout()
plt.show()
notion:
subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,
subplot_kw=None, gridspec_kw=None, **fig_kw):
eg:
fig, ax = plt.subplots(8, 8, figsize=(8, 8), dpi=100, squeeze=False)
输入参数说明:
nrows,ncols:整型,可选参数,默认为1。表示子图网格(grid)的行数与列数。
sharex,sharey:布尔值或者{'none','all','row','col'},默认:False
控制x(sharex)或y(sharey)轴之间的属性共享:
1.True或者'all':x或y轴属性将在所有子图(subplots)中共享.
2.False或'none':每个子图的x或y轴都是独立的部分
3.'row':每个子图在一个x或y轴共享行(row)
4.'col':每个子图在一个x或y轴共享列(column)
当子图在x轴有一个共享列时('col'),只有底部子图的x tick标记是可视的。
同理,当子图在y轴有一个共享行时('row'),只有第一列子图的y tick标记是可视的。
squeeze:布尔类型,可选参数,默认:True。
如果是True,额外的维度从返回的Axes(轴)对象中挤出。
如果只有一个子图被构建(nrows=ncols=1),结果是单个Axes对象作为标量被返回。
对于N*1或1*N个子图,返回一个1维数组。
对于N*M,N>1和M>1返回一个2维数组。
如果是False,不进行挤压操作:返回一个元素为Axes实例的2维数组,即使它最终是1x1。
subplot_kw:字典类型,可选参数。把字典的关键字传递给add_subplot()来创建每个子图。
gridspec_kw字典类型,可选参数。把字典的关键字传递给GridSpec构造函数创建子图放在网格里(grid)。
**fig_kw:把所有详细的关键字参数传给figure()函数
返回结果:
fig:matplotlib.figure.Figure对象
ax:Axes(轴)对象或Axes(轴)对象数组。
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec
#------------------------------------------------------------plot in plot-------------------------------------
fig1 = plt.figure(5)
x = [1,2,3,4,5,6,7]
y = [1,3,6,2,7,9,12]
#大图坐标
#4个值都是占整个figure坐标系的百分比。EG:假设figure大小是10x10,那么大图就被包含在由(1, 1)开始,宽9,高9的坐标系内。
left,bottom,width,height = 0.1,0.1,0.9,0.9
#将坐标加到大图里面
ax1 = fig1.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('Big Image')
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
ax2 = fig1.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('little image_1')
plt.axes([0.6, 0.2, 0.25, 0.25])
#对y进行了逆序处理
plt.plot(y[::-1], x, 'g')
plt.xlabel('x')
plt.ylabel('y')
plt.title('little image_2')
plt.show()
#----------------------------------------------------axis-------------------------------------------------------
x3 = np.arange(0, 10, 0.1)
y3 = 0.05 * x3**2
y4 = -1 * y3
fig2 , ax3 = plt.subplots() #subplots
#twinx():生成镜面效果后的ax2
ax4 = ax3.twinx()
ax3.plot(x3, y3, 'g-') # green, solid line
ax3.set_xlabel('X3 data')
ax3.set_ylabel('Y3 data', color='g')
ax4.plot(x3, y4, 'b-') # blue
ax4.set_ylabel('Y4 data', color='b')
plt.show()
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# http://matplotlib.sourceforge.net/api/animation_api.html
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x + i/10.0)) # update the data
return line,
def init():
line.set_ydata(np.sin(x))
return line,
# blit=True Mac上为False; interval= 更新频率
anim = animation.FuncAnimation(fig=fig, func=animate, frames=100, init_func=init,
interval=20, blit=False)
#anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()