开发者社区> 问答> 正文

在python中的图形上绘制常量文本

我确定我可能在问一个愚蠢的问题,但找不到与我相同的问题。

我的朋友帮我写了一段代码,分析给出的数据并用趋势线将其绘制出来,我想在图的右上方添加一行文本,并在图上打印出其他内容,以表明它是什么文件(在代码的其他地方以常量形式编写)。

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from numpy import exp, loadtxt, pi, sqrt, random, linspace
from lmfit import Model
import glob, os

## Define gaussian
def gaussian(x, amp, cen, wid):
    """1-d gaussian: gaussian(x, amp, cen, wid)"""
    return (amp / (sqrt(2\*i) * wid)) * exp(-(x-cen)\*2 / (2\*id\*2))

## Define exponential decay
def expdecay(x, t, A): 
     return A\*xp(-x/t)

## Define constants
fileToRun = 'Run15'
folderId = '\\'
baseFolder = 'C:'+folderId+'Users'+folderId+'ControlRoom6'+folderId+'Documents'+folderId+'PhD'+folderId+'Ubuntu-Analysis-DCF'+folderId+'DCF-an-b+decay'+folderId+'dcp-ap-27Al'+folderId+''
prefix = 'DECAY_COINC'
stderrThreshold = 10
minimumAmplitude = 0.1
approxcen = 780
MaestroT = 18

## Define paramaters
amps = []; ampserr = []; ts = []
folderToAnalyze = baseFolder + fileToRun + '\\'

## Gets number of files
files = []
os.chdir(folderToAnalyze)
for file in glob.glob(prefix + "\*Spe"):
    files.append(file)
numfiles = len(files)
if numfiles<=1:
    print('numfiles is {0}, minimum of 2 is required'.format(numfiles))
    raise SystemExit(0)

## Generate the time array

for n in range(0, numfiles):

    ## Print progress
    print('\rFile {0} / {1}'.format(n+1, numfiles), end='')

    ## Load text file
    x = np.linspace(0, 8191, 8192) 
    fullprefix = folderToAnalyze + prefix + str(n).zfill(3)
    y = loadtxt(fullprefix + ".Spe", skiprows= 12, max_rows = 8192) 

    ## Make figure
    fig, ax = plt.subplots(figsize=(15,8))
    fig.suptitle('Coincidence Detections', fontsize=20)
    plt.xlabel('Bins', fontsize=14)
    plt.ylabel('Counts', fontsize=14)

    ## Plot data
    ax.plot(x, y, 'bo')
    ax.set_xlim(600,1000)

    ## Fit data to Gaussian
    gmodel = Model(gaussian)
    result = gmodel.fit(y, x=x, amp=8, cen=approxcen, wid=1)

    ## Plot results and save figure
    ax.plot(x, result.best_fit, 'r-', label='best fit')
    ax.legend(loc='best')
    texttoplot = result.fit_report()
    ax.text(0.02, 0.5, texttoplot, transform=ax.transAxes)
    plt.close()
    fig.savefig(fullprefix + ".png", pad_inches='0.5')

    ## Print progress
    if n==numfiles-1:
        print('\rDone')

    ## Append to list if error in amplitude and amplitude itself is within reasonable bounds
    if result.params['amp'].stderr < stderrThreshold and result.params['amp'] > minimumAmplitude:
        amps.append(result.params['amp'].value) 
        ampserr.append(result.params['amp'].stderr) 
        ts.append(MaestroT\*)

## Plot decay curve
fig, ax = plt.subplots()
ax.errorbar(ts, amps, yerr= 2\*p.array(ampserr), fmt="ko-", capsize = 5, capthick= 2, elinewidth=3, markersize=5)
plt.xlabel('Time', fontsize=14)
plt.ylabel('Peak amplitude', fontsize=14)

## Fit decay curve
emodel = Model(expdecay)
decayresult = emodel.fit(amps, x=ts, weights=1/np.array(ampserr), t=150, A=140)
ax.plot(ts, decayresult.best_fit, 'r-', label='best fit')

## Add text to plot
plottext = '{filetoRun}\n'
plottext = 'N: {0} / {1}\n'.format(len(ts), numfiles)
plottext += 't: {0:.2f} ± {1:.2f}\n'.format(decayresult.params['t'].value, decayresult.params['t'].stderr)
plottext += 'A: {0:.2f} ± {1:.2f}\n'.format(decayresult.params['A'].value, decayresult.params['A'].stderr)
plottext += 'Reduced $χ^2$: {0:.2f}\n'.format(decayresult.redchi)
ax.text(0.5, 0.55, plottext, transform=ax.transAxes, fontsize=14)
plt.show()

## Save figure
fig.savefig(folderToAnalyze + "A_" + prefix + "_decayplot.pdf", pad_inches='0.5')

我想要它(在这种情况下,Run15显示在该图中显示“ N = 28/50”的上方)。我已经尝试了方括号和plt.text的各种组合,但是说实话,我真的不知道自己在做什么,这对我来说是全新的。它不会出现这样的错误,只输出没有所需文本的图形

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 23:34:31 513 0
1 条回答
写回答
取消 提交回答
  • 我认为您使用=而不是+ =犯了一个错误,这就是使用fileToRun无法打印第一行的原因。

    除此之外,在字符串中的变量周围加上方括号'{filetoRun} \ n'的直觉很有意义:这就是Python f字符串的目的!您只需要在字符串前使用f说明符即可。

    替换为:

    plottext = '{fileToRun}\n'
    plottext = 'N: {0} / {1}\n'.format(len(ts), numfiles)
    

    这样:

    plottext = f'{fileToRun}\n'
    plottext += 'N: {0} / {1}\n'.format(len(ts), numfiles)
    

    顺便说一句好情节!

    回答来源:stackoverflow

    2020-03-24 23:34:40
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载