一、第一章
1.基本用法
import matplotlib.pyplot as plt
import numpy as npx = np.linspace(-1,1,50)
y = 2*x + 1
plt.plot(x,y)
plt.show()
2.figure图像
import matplotlib.pyplot as plt
import numpy as npx = np.linspace(-1,1,50)
y1 = 2*x + 1
y2 = x**2
plt.figure()
plt.plot(x,y1)
plt.figure()
#plt.figure(num= ,figsize(长,宽))
plt.plot(x,y2)
plt.show()
import matplotlib.pyplot as plt
import numpy as npx = np.linspace(-1,1,50)
y1 = 2*x + 1
y2 = x**2
plt.figure()
plt.plot(x,y1)
plt.figure()
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.show()
3.设置坐标轴1
import matplotlib.pyplot as plt
import numpy as npx = np.linspace(-1,1,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.2,3],[r"$really\ bad$",r"$bad\ \alpha$",r"$normal$",r"$good$",r"$really\ good$"])
plt.show()
4.设置坐标轴2
import matplotlib.pyplot as plt
import numpy as npx = np.linspace(-1,1,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.2,3],[r"$really\ bad$",r"$bad\ \alpha$",r"$normal$",r"$good$",r"$really\ good$"])
#gc = 'get current axis'
ax = plt.gca()
#设置框架(上下左右的线条)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))
plt.show()
5.legend图例
import matplotlib.pyplot as plt
import numpy as npx = np.linspace(-1,3,50)
y1 = 2*x + 1
y2 = x**2
plt.figure()#取值范围
plt.xlim((-1,3))
plt.ylim((-2,3))
plt.xlabel("I am X")
plt.ylabel("I am Y")new_ticks = np.linspace(-1,3,5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2,-1.8,-1,1.2,3],[r"$really\ bad$",r"$bad\ \alpha$",r"$normal$",r"$good$",r"$really\ good$"])l1,=plt.plot(x,y2,label='up')
l2,=plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--',label='down')
plt.legend(handles=[l1,l2],labels=['a','b'],loc='best')plt.show()
6.Annotation标注
import matplotlib.pyplot as plt
import numpy as npx = np.linspace(-3,3,50)
y = 2*x + 1
plt.figure(num=1,figsize=(8,5))
plt.plot(x,y)#gc = 'get current axis'
ax = plt.gca()
#设置框架(上下左右的线条)
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0))
ax.spines['left'].set_position(('data',0))#添加点
x0 = 1
y0 = 2*x0 + 1
plt.scatter(x0,y0,s=50,color='b')
#添加虚线
plt.plot([x0,x0],[y0,0],'k--',lw=2.5)
#Annotation,method1:
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'))
#Annotation,method2:
plt.text(-3.7,3,r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',fontdict={'size':16,'color':'r'})plt.show()
7.tick能见度
import matplotlib.pyplot as plt
import numpy as npx = np.linspace(-3,3,50)
y = 0.1 * x
plt.figure()
plt.plot(x,y,linewidth=10)
plt.ylim(-2,2)
#gc = 'get current axis'
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.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0))
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()
二、第二章
1.散点图
import numpy as np
import matplotlib.pyplot as pltn = 1024
X = np.random.normal(0,1,n)
Y = np.random.normal(0,1,n)
T = np.arctan2(Y,X) #设置颜色
plt.scatter(X,Y,c=T,s=75,alpha=0.5)
plt.xlim(-1.5,1.5)
plt.ylim(-1.5,1.5)
plt.xticks(())
plt.yticks(())
plt.show()
2.柱状图
import matplotlib.pyplot as plt
import numpy as npn = 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,facecolor='#9999ff',edgecolor='white')
#向下
plt.bar(X,-Y2,facecolor='#ff9999',edgecolor='white')
#加数字
for x,y in zip(X,Y1):#ha:横向对齐方式;va:纵向对齐方式plt.text(x + 0.4,y+0.05,'%.2f'%y,ha='center',va='bottom')
for x,y in zip(X,Y2):#ha:横向对齐方式;va:纵向对齐方式plt.text(x + 0.4,-y-0.05,'-%.2f'%y,ha='center',va='top')
plt.xlim(-5,n)
plt.xticks(())
plt.ylim(-1.25,1.25)
plt.yticks(())
plt.show()
3.等高线图
import matplotlib.pyplot as plt
import numpy as np
def f(x,y):#计算高度的方法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) #构建坐标网络
#创建轮廓图,alpha为轮廓透明度,cmap为轮廓颜色映射
plt.contour(X,Y,f(X,Y),8,alpha=0.75,cmap=plt.cm.hot)
#画等高线
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)
"""
for the value of "interpolation", check this:
http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
for the value of "origin"= ['upper', 'lower'], check this:
http://matplotlib.org/examples/pylab_examples/image_origin.html
"""
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
#颜色条
plt.colorbar(shrink=.92)
plt.xticks(())
plt.yticks(())
plt.show()
5.3D数据
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D #导入3D包
fig = plt.figure() #窗口
#ax = Axes3D(fig) #显示不出来
ax = fig.add_axes(Axes3D(fig)) # 替代上行代码
# X, Y 数组
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)
# height value
Z = np.sin(R)
#画在ax上,rstride、cstride跨度(行列),
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)
plt.show()
三、第三章
1.Subplot多合一显示
import matplotlib.pyplot as plt
#练习1
plt.figure(figsize=(6, 4))
# 两行两列,第一张图
plt.subplot(2, 2, 1)
#x,y的坐标
plt.plot([0, 1], [0, 1])
# 两行两列,第二张图
plt.subplot(222)
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.tight_layout()# 练习2:
plt.figure(figsize=(6, 4))
# 两行,第一列的图占了3格
plt.subplot(2, 1, 1)
plt.plot([0, 1], [0, 1])
# 两行,第二列的第一个图
plt.subplot(234)
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.tight_layout()
plt.show()
2.Subplot分格显示
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec# 方法 1: subplot2grid
plt.figure()
#三行三列 从1行1列开始 ,跨度(列)是3
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3)
ax1.plot([1, 2], [1, 2])
ax1.set_title('ax1_title')
#三行三列 从2行1列开始 ,跨度(列)是2
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
#三行三列 从2行3列开始 ,跨度(行)是2
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
#三行三列 从3行1列开始
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax4.scatter([1, 2], [2, 2])
ax4.set_xlabel('ax4_x')
ax4.set_ylabel('ax4_y')
#三行三列 从3行2列开始
ax5 = plt.subplot2grid((3, 3), (2, 1))# 方法 2: gridspec
plt.figure()
gs = gridspec.GridSpec(3, 3)
#第1行占所有列
ax6 = plt.subplot(gs[0, :])
#第2行,占了前2列
ax7 = plt.subplot(gs[1, :2])
#从2行开始到最后的行,第三列
ax8 = plt.subplot(gs[1:, 2])
#最后一行第一列
ax9 = plt.subplot(gs[-1, 0])
#最后一行,后两列
ax10 = plt.subplot(gs[-1, -2])# 方法 3: 共享X,Y轴
f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1,2], [1,2])plt.tight_layout()
plt.show()
3.图中图
import matplotlib.pyplot as pltfig = plt.figure()
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
#整个图的占比0.1=10%
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
#大图
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')
#小图1
ax2 = fig.add_axes([0.2, 0.6, 0.25, 0.25])
ax2.plot(y, x, 'b')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')
#小图2
plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1], x, 'g')
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')plt.show()
4.次坐标轴
import matplotlib.pyplot as plt
import numpy as npx = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 *y1
fig, ax1 = plt.subplots()
ax2 = ax1.twinx() # 颠倒
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')
plt.show()
5.Animation动画
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
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))return line,def init():line.set_ydata(np.sin(x))return line,
ani = animation.FuncAnimation(fig=fig, func=animate, frames=100, init_func=init,interval=20, blit=False)plt.show()
注意:图片其实是一个动画