Python绘图笔记

此例子包含的内容:

  1. 用subplot绘制2×2的子图组合,每个子图中包含两条曲线
  2. 读取数据文本的方法
  3. 曲线配色方法,线宽
  4. 坐标轴标题设置,坐标轴范围,坐标刻度设置
  5. 图例的添加方法
  6. 特殊字符(数学公式)的输入方法
  7. 图片保存
import matplotlib.pyplot as plt
import numpy as np

plt.figure()

# A = 82; Z = 32,33
p1 = plt.subplot(2,2,1) 
data1 = np.loadtxt("E:\Documents\MyJob\Exp.Data\G4SpecificEnergy\Z32A82.txt")
p1.plot(data1[:,0],data1[:,1],color='k',linewidth=2.5)
data2 = np.loadtxt("E:\Documents\MyJob\Exp.Data\G4SpecificEnergy\Z33A82.txt")
p1.plot(data2[:,0],data2[:,1],color='#8696a7',linewidth=2.5)
p1.set_xlabel('Range(mm)')
p1.set_ylabel('dE/dx (MeV/mm)')
#p1.grid(linestyle='-.')
plt.xlim(0,185)
plt.ylim(0,1.05)
plt.xticks(np.arange(0,185,40))
# set the legend
A, = p1.plot(data1[:,0],data1[:,1],color='k')
B, = p1.plot(data2[:,0],data2[:,1],color='#8696a7')
plt.legend(handles = [A,B],labels = ["Z=32,A=82","Z=33,A=82"],loc = 'upper right')

# A = 97; Z = 38,39
p2 = plt.subplot(2,2,2)
data3 = np.loadtxt("E:\Documents\MyJob\Exp.Data\G4SpecificEnergy\Z38A97.txt")
p2.plot(data3[:,0],data3[:,1],color='k',linewidth=2.5)
data4 = np.loadtxt("E:\Documents\MyJob\Exp.Data\G4SpecificEnergy\Z39A97.txt")
p2.plot(data4[:,0],data4[:,1],color='#8696a7',linewidth=2.5)
p2.set_xlabel('Range(mm)')
p2.set_ylabel('dE/dx (MeV/mm)')
plt.xlim(0,165)
plt.ylim(0,1.26)
plt.xticks(np.arange(0,165,40))
A, = p2.plot(data3[:,0],data3[:,1],color='k')
B, = p2.plot(data4[:,0],data4[:,1],color='#8696a7')
plt.legend(handles = [A,B],labels = ["Z=38,A=97","Z=39,A=97"],loc = 'upper right')

# A = 108; Z = 44,45
p3 = plt.subplot(2,2,3)
data5 = np.loadtxt("E:\Documents\MyJob\Exp.Data\G4SpecificEnergy\Z44A108.txt")
p3.plot(data5[:,0],data5[:,1],color='k',linewidth=2.5)
data6 = np.loadtxt("E:\Documents\MyJob\Exp.Data\G4SpecificEnergy\Z45A108.txt")
p3.plot(data6[:,0],data6[:,1],color='#8696a7',linewidth=2.5)
p3.set_xlabel('Range(mm)')
p3.set_ylabel('dE/dx (MeV/mm)')
plt.xlim(0,125)
plt.ylim(0,1.55)
plt.xticks(np.arange(0,125,40))
A, = p3.plot(data5[:,0],data5[:,1],color='k')
B, = p3.plot(data6[:,0],data6[:,1],color='#8696a7')
plt.legend(handles = [A,B],labels = ["Z=44,A=108","Z=45,A=108"],loc = 'upper right')

# A = 130; Z = 50,51
p4 = plt.subplot(2,2,4)
data7 = np.loadtxt("E:\Documents\MyJob\Exp.Data\G4SpecificEnergy\Z50A130.txt")
p4.plot(data7[:,0],data7[:,1],color='k',linewidth=2.5)
data8 = np.loadtxt("E:\Documents\MyJob\Exp.Data\G4SpecificEnergy\Z51A130.txt")
p4.plot(data8[:,0],data8[:,1],color='#8696a7',linewidth=2.5)
p4.set_xlabel('Range($\mu$m)')
p4.set_ylabel('dE/dx (MeV/mm)')
plt.xlim(0,125)
plt.ylim(0,1.45)
plt.xticks(np.arange(0,125,40))
A, = p4.plot(data7[:,0],data7[:,1],color='k')
B, = p4.plot(data8[:,0],data8[:,1],color='#8696a7')
plt.legend(handles = [A,B],labels = ["Z=50,A=130","Z=51,A=130"],loc = 'upper right')

plt.show()
#保存图片
plt.savefig('E:/meanKE.png')

推荐阅读更多精彩内容