import matplotlib.pyplot as plt
def read_file(file):
"""读数据到列表,映射为浮点数"""
with open(file) as data: # 用上下文管理器打开文件,创建文件对象
data.readline()
txt_to_list = [list(map(float, line.strip().split())) for line in data.readlines()] # 遍历文件
return txt_to_list
# 找出纵坐标值最大的5个峰的坐标
def top_peak(xrd_in_list):
"""接收列表数据,返回纵标值最大的5组数据的列表"""
sort_of_ls = sorted(xrd_in_list, key=lambda item: item[1], reverse=True)[:5]
return sort_of_ls
def mark_peak(sort_of_ls):
"""接收排序的数据,绘制注释"""
for x, y in sort_of_ls:
plt.annotate(f'{y}', xy=(x, y), xytext=(+30, 0),
textcoords='offset points', fontsize=12,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
def plot_xrd(xrd_in_list, sort_of_ls):
"""接收数据列表和排序的数据,绘制曲线和注释"""
lsx = [data[0] for data in xrd_in_list] # 创建空列表,分别容纳x,y坐标数据
lsy = [data[1] for data in xrd_in_list]
plt.plot(lsx, lsy, color='green') # 绘制数据曲线,默认颜色
plt.axhline(0, linestyle='--', color='red')
plt.axvline(0, linestyle='--', color='blue')
plt.title('X射线衍射图谱', fontproperties='SimHei')
plt.xlabel('2d')
plt.ylabel('Intensity')
mark_peak(sort_of_ls)
plt.show()
if __name__ == '__main__':
filename = 'XRD_AFO.txt'
xrd_data = read_file(filename)
sort_of_xrd = top_peak(xrd_data)
plot_xrd(xrd_data, sort_of_xrd)
扫描下方二维码,关注后了解更多精彩内容!!