注释图形中的兴趣点(Matplotlib)

2024-05-29 02:45:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的图形中的一个感兴趣的点上注释和画一条线。我已经为它编写了一个代码,它可以完成工作。在

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
fsource=('/Users/Maxwell/Desktop/OES data.xlsx')
df=pd.read_excel(fsource,header = 1, parse_cols = "C:D",names=['Wavelength','Intensity'])
fig1 = plt.figure()
f, ax = plt.subplots(1, figsize = (8,4))
ax.set_xlabel('Wavelength',fontsize=15)
ax.set_ylabel('Intensity',fontsize=15)
ax.plot(df['Wavelength'],df['Intensity'],color='red')
ax.set_xlim(xmin=400,xmax=800)
ax.set_ylim(ymin=0,ymax=5000) #Specify the max and min of y axis
ax.tick_params(axis= 'both', labelsize=12) #fontsize of x & y ticks as 12
ax.axvline(x= 604,color='black',ymin=0.05, ymax=0.5) #x=604 is my point of interest.
ax.annotate('POF-1', xy=(604, 2400),fontsize=12)
plt.show()

关于这种方法/程序,我有一些问题:

  1. 有没有更有效/更好的方法来做同样的工作?(对代码等的任何改进)

  2. 我的代码只适用于一个感兴趣的点“POF-1”。如果我有几个感兴趣的点,我将不得不一个一个地给它们编号,并且一遍又一遍地指定线的长度。我应该怎么做才能使任务自动化,这样注释和线条同时出现在所有感兴趣的点上?(例如,用一些预定义的文本注释点x=500、730、790等)。

原始文件的链接是link中的OES data


Tags: of代码importdfaspltax感兴趣
1条回答
网友
1楼 · 发布于 2024-05-29 02:45:43

您可以在要注释的点上循环:

xs = [500, 730, 790]
texts = ["POF-1", "Some peak", "another peak"]
for x, t in zip(xs, texts):
    ax.axvline(x=x, color='black',ymin=0.05, ymax=0.5)
    ax.annotate(t, xy=(x, 2400),fontsize=12)

相关问题 更多 >

    热门问题