学习笔记手札及单元小结
Matplotlib库的使用
import matplotlib.pyplot as plt #引入matplotlib库,模块的别名为plt
Matplotlib库综合小测
import matplotlib.pyplot as plt
plt.plot([3,1,4,5,2])
plt.ylabel("Grade")
plt.show()
import matplotlib.pyplot as plt
plt.plot([3,1,4,5,2])
plt.ylabel("Grade")
plt.savefig('test', dpi=600)#存成PNG文件,可以通过dpi修改输出质量
plt.show()
import matplotlib.pyplot as plt
plt.plot([0,2,4,6,8],[3,1,4,5,2]) #注意当有两个以上参数时,按照x轴和y轴顺序绘制数据点
plt.ylabel("Grade")
plt.axis([-1,10,0,6])
plt.show()
pyplot的绘图区域
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
a = np.arange(0.0,5.0,0.02)
plt.subplot(211)
plt.plot(a,f(a))
plt.subplot(2,1,2)
plt.plot(a,np.cos(2*np.pi*t2),'r--') #此处代码报错,t2未被赋值
plt.show()
pyplot的plot()函数
import matplotlib.pyplot as plt
import numpy as np
a = np.arange(10)
plt.plot(a,a*1.5,a,a*2.5,a,a*3.5,a,a*4.5)
plt.show()
import matplotlib.pyplot as plt
import numpy as np
a = np.arange(10)
plt.plot(a,a*1.5,'go-',a,a*2.5,'rx',a,a*3.5,'*',a,a*4.5,'b-.')
plt.show()
颜色字符,风格字符和标记字符可以组合使用
pyplot的中文显示
第一种方法
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family']='SimHei' #'SimHei'是黑体
plt.plot([3,1,4,5,2])
plt.ylabel("纵轴(值)")
plt.savefig('test',dpi=600)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family']='STSong'
matplotlib.rcParams['font.size']=20
a = np.arange(0.0,5.0,0.02)
plt.xlabel('横轴:时间')
plt.ylabel('纵轴:振幅')
plt.plot(a,np.cos(2*np.pi*a),'r--')
plt.show()
第二种方法,在有中文输出的地方,增加一个属性:fontproperties
import numpy as np
import matplotlib.pyplot as plt
a = np.arange(0.0,5.0,0.02)
plt.xlabel('横轴:时间',fontproperties='SimHei',fontsize=20)
plt.ylabel('纵轴:振幅',fontproperties='SimHei',fontsize=20)
plt.plot(a,np.cos(2*np.pi*a),'r--')
plt.show()
pyplot的文本显示
实例
import numpy as np
import matplotlib.pyplot as plt
a = np.arange(0.0,5.0,0.02)
plt.plot(a,np.cos(2*np.pi*a),'r--')
plt.xlabel('横轴:时间',fontproperties='SimHei',fontsize=15,color='green')
plt.ylabel('纵轴:振幅',fontproperties='SimHei',fontsize=15)
plt.title(r'正弦波实例 $y=cos(2\pi x)$',fontproperties='SimHei',fontsize=25)
plt.text(2,1,r'$\mu=100$',fontsize=15)
plt.axis([-1,6,-2,2])
plt.grid(True)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
a = np.arange(0.0,5.0,0.02)
plt.plot(a,np.cos(2*np.pi*a),'r--')
plt.xlabel('横轴:时间',fontproperties='SimHei',fontsize=25,color='green')
plt.ylabel('纵轴:振幅',fontproperties='SimHei',fontsize=25)
plt.title(r'正弦波实例 $y=cos(2\pi x)$',fontproperties='SimHei',fontsize=25)
plt.annotate(r'$\mu=100$',xy=(2,1),xytext=(3,1.5),
arrowprops=dict(facecolor='black',shrink=0.1,width=2))
plt.axis([-1,6,-2,2])
plt.grid(True)
plt.show()
pyplot的子绘图区域
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
gs = gridspec.GridSpec(3,3)
ax1 = plt.subplot(gs[0,:])
ax2 = plt.subplot(gs[1,:-1])
ax3 = plt.subplot(gs[1:,-1])
ax4 = plt.subplot(gs[2,0])
ax5 = plt.subplot(gs[2,1])