(以下展示均为先图片后代码的形式。)
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> x = np.linspace(-1.,1.,50)
>>> y = x**2 + 1
>>> plt.plot(x,y)
>>> plt.show()
—————————————————————————————
多窗口(多函数)
>>> plt.figure('first window')
>>> y1 = np.sqrt(-x**2 + 1)
>>> plt.plot(x,y1)
>>> plt.figure('second window')
>>> y2 = np.sqrt(x**2 + 1)
>>> y3 = x**3 + 1
>>> plt.plot(x,y2)
>>> plt.plot(x,y3)
>>> plt.show()
—————————————————————————————
更多例子
>>> plt.plot(x,y1,'g-',x,y2,'b--',x,y3,'r.')
>>> plt.show()
—————————————————————————————
>>> plt.figure('graph1')
>>> plt.xlabel('x轴')
>>> plt.ylabel('y轴')
>>> y = 2**x - 3
>>> plt.plot(x,y,'r*')
>>> plt.show()
—————————————————————————————
>>> plt.xlim((-1,1)) #设置坐标轴初次显示的范围
(-1,1)
>>> plt.ylim((1,2))
(1,2)
>>> plt.xlabel('i\'m x.') #设置坐标轴名称
>>> plt.ylabel('i\'m y.')
>>> plt.xticks([-1,-0.5,0,0.5,1]) #设置x的显示步长
([,,,,],)
>>> plt.yticks([1,1.2,2],['bad','normal','good'])
([,,],)
>>> y1 = x + 1.5
>>> y2 = x**2 + 1
>>> plt.plot(x,y1,'go',x,y2,'b--')
>>> plt.show()
—————————————————————————————
>>> plt.plot(x,y1,color='red',linewidth=2.0,linestyle='--',label='function1')
>>> plt.plot(x,y2,color='green',linewidth=1.0,linestyle='-',label='function2')
>>> plt.legend(loc='lower right') # loc可以为‘best’:自动找一个数据少的地方显示
>>> plt.show()
—————————————————————————————
>>> x = np.random.randint(1,50,size=(50,))
>>> y1 = np.random.randint(1,50,size=(50,))
>>> y2 = np.random.randint(1,50,size=(50,))
>>> plt.xticks(())
>>> plt.yticks(())
>>> plt.scatter(x,y1,c='red') #画散点图
>>> plt.scatter(x,y2,c='blue')
>>> plt.show()
—————————————————————————————
### ‘图像更新’
plt.ion() # 打开交互模式
plt.plot(x,y) #显示图像
plt.pause(0.01) # 暂停功能
plt.clf() # 清除当前的Figure对象
plt.cla() # 清除当前的Axes对象
plt.ioff() #关闭交互模式
以上功能在for循环中可实现图像(x,y)更新
—————————————————————————————
>>> x=np.array(np.arange(1,2,0.01))
>>> y=np.array(np.arange(1,2,0.01))
>>> xx,yy = np.meshgrid(x,y)#将x、y分别往纵向和横向扩展成2d数组
>>> xx
array([[1. , 1.01, 1.02,..., 1.97, 1.98, 1.99],
[1. , 1.01, 1.02,..., 1.97, 1.98, 1.99],
[1. , 1.01, 1.02,..., 1.97, 1.98, 1.99],
...,
[1. , 1.01, 1.02,..., 1.97, 1.98, 1.99],
[1. , 1.01, 1.02,..., 1.97, 1.98, 1.99],
[1. , 1.01, 1.02,..., 1.97, 1.98, 1.99]])
>>> yy
array([[1. , 1. , 1. ,..., 1. , 1. , 1. ],
[1.01, 1.01, 1.01,..., 1.01, 1.01, 1.01],
[1.02, 1.02, 1.02,..., 1.02, 1.02, 1.02],
...,
[1.97, 1.97, 1.97,..., 1.97, 1.97, 1.97],
[1.98, 1.98, 1.98,..., 1.98, 1.98, 1.98],
[1.99, 1.99, 1.99,..., 1.99, 1.99, 1.99]])
>>> z=xx*yy < 2 #定义第三维的高度:等于1 or 0
>>> plt.contourf(xx,yy,z,alpha=0.4)#创建等高图对象
>>> plt.show()