【问题标题】:Plotting a constant text on a graph in python在python中的图形上绘制常量文本
【发布时间】:2020-03-06 12:17:15
【问题描述】:

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

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

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*pi) * wid)) * exp(-(x-cen)**2 / (2*wid**2))

## Define exponential decay
def expdecay(x, t, A): 
     return A*exp(-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*n)

## Plot decay curve
fig, ax = plt.subplots()
ax.errorbar(ts, amps, yerr= 2*np.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 的组合,但老实说,我真的不知道我在做什么,这对我来说是全新的。它不会出现这样的错误,只是输出没有所需文本的图形

【问题讨论】:

  • 为什么要在 filetoRun 周围加上括号?试试这个:plottext = filetoRun + '\n'
  • 老实说,我只是尝试了一堆不同的东西,使用 ()、使用 {}、使用 []、使用 /n、使用 '' 以及没有所有这些。使用 plt.text。就像我说的,我真的不知道自己在做什么,试图以身作则并在可能的情况下提供友好的帮助:-)
  • NameError Traceback (最近一次调用最后一次) in 95 96 ## 添加文本到绘图 ---> 97 plottext = filetoRun + '\n' 98 plottext = 'N: {0} / {1}\n'.format(len(ts), numfiles) 99 plottext += 't: {0:.2f} ± {1:.2f}\n'。 format(decayresult.params['t'].value, decayresult.params['t'].stderr) NameError: name 'filetoRun' is not defined ^^^这是我用 plottext = filetoRun + '\n' 得到的改为第 97 行

标签: python python-3.x matplotlib plot text


【解决方案1】:

我认为您使用= 而不是+= 时犯了一个错误,这就是无法使用fileToRun 打印第一行的原因。

除此之外,您对在字符串中的变量周围加上括号 '{filetoRun}\n' 的直觉是有道理的:这就是 Python f-strings 的目的!您只需要在字符串前使用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)

顺便说一句,剧情不错!

【讨论】:

  • 恐怕还是没有运气:NameError Traceback (最近一次调用最后一次) in 95 96 ## 添加文本到绘图 ---> 97 plottext = f'{filetoRun}\n' 98 plottext = 'N: {0} / {1}\n'.format(len(ts), numfiles) 99 plottext += 't: {0:.2f} ± {1:.2f}\n'.format(decayresult.params['t'].value, decayresult.params['t'].stderr) NameError: name 'filetoRun' is not defined
  • 另外,感谢您对剧情的称赞。恐怕我不能接受所有的功劳,或者大部分功劳,哈哈。我只是“设计”了它,另一个人编写了大部分代码
  • 看看错误,上面写着filetoRun is not defined:当您在上面使用fileToRun = 'Run15' 定义它时,这怎么可能?你又跑了一遍吗?
  • 这是 'filestoRun' 中的 t,应该是 'filesToRun'。再加上第 98 行的 += 和您建议的 f 字符串!
  • 哈!谢谢,正想问你是否介意这样做!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-20
  • 1970-01-01
相关资源
最近更新 更多