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

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

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

python中用于绘制各种图形、标注文本_在python中的图形上绘制常量文本-问答-阿里云开发者社区-阿里云...相关推荐

  1. python合法标识符 40xl_Python基础测验(答案篇)-问答-阿里云开发者社区-阿里云

    一.填空题 Python使用符号 # 标示单行注释:以 缩进对齐 划分语句块. Python序列类型包括 字符串 . 列表 . 元组 三种: _字典_是Python中唯一的映射类型. Python序列 ...

  2. python中str用法_python中的str()不能直接用吗 -问答-阿里云开发者社区-阿里云

    str函数是Python的内置函数,它将参数转换成字符串类型,即人适合阅读的形式. 其语法格式为 1 str(object) 返回值: 返回object的字符串形式 使用示例 无参调用 当str()函 ...

  3. python如何实时捕捉cmd显示_如何从Python脚本中捕获Python解释器和/或CMD.EXE的输出? -问答-阿里云开发者社区-阿里云...

    如果您正在谈论python解释器或CMD.exe,它是您脚本的"父",那么不可能.在每个类似POSIX的系统中(现在你正在运行Windows,看起来可能有一些我不知道的怪癖,YMM ...

  4. python语言打小数点_如何在python中打小数点-问答-阿里云开发者社区-阿里云

    python提供了三种浮点值:内置的float与complex类型,以及标准库的decimal.Decimal类型. float类型存放双精度的浮点数,具体取值范围依赖于构建python的c编译器,由 ...

  5. python键盘怎么输入双引号_python中怎么输入引号 -问答-阿里云开发者社区-阿里云...

    Python中的引号可分为单引号.双引号和三引号. 在Python中我们都知道单引号和双引号都可以用来表示一个字符串,比如 str1 = 'python' str2 = "python&qu ...

  6. python中如何输出中文_python中怎么输出中文-问答-阿里云开发者社区-阿里云

    方法一: 用encode和decode 如: ? 1 2 3 4 5 6 7 8 9 10 11 import os.path import xlrd,sys Filename='/home/tom/ ...

  7. python if else用法同一行_在Python的同一行中使用if else for和del吗?-问答-阿里云开发者社区-阿里云...

    我有一个列表,其项目是可变长度的列表. 如果这些可变长度的列表项超过此长度,则需要将其截断为特定长度(x). 我做了这个小的功能. def truncateList(batch_, trim_len) ...

  8. python中右对齐_python中如何右对齐-问答-阿里云开发者社区-阿里云

    例如,有一个字典如下: dic = { "name": "botoo", "url": "http://www.123.com&q ...

  9. python中tmp什么意思_python中temp是什么意思-问答-阿里云开发者社区-阿里云

    ==tempfile 模块== [Example 2-6 #eg-2-6] 中展示的 tempfile 模块允许你快速地创建名称唯一的临时文件供使用. ====Example 2-6. 使用 temp ...

最新文章

  1. 参数估计Bayesian方法的困惑点
  2. 中小企业应如何选择合适的数据保护工具?
  3. SharePoint文档上传管理
  4. c++ eos智能合约开发_[EOS智能合约]第二节:用EOS开发一个To-do List小应用
  5. 字符设备驱动高级篇2——字符设备驱动注册代码分析
  6. Incorrect string value: '/xE7/xA8/x8B/xE5/xBA/x8F...' for column 'course' at row 1
  7. TensorFlow 2.0简介
  8. 没事做贴个代码,判断是否素数,顺便打个素数表(非原创)。
  9. group by两个条件
  10. mysql存储过程返回结果集_原来MySQL的存储过程也可以这么玩?
  11. 愿望实现了!办公软件全部装进口袋
  12. ios 融云 重写对话列表_iOS消息体系架构详解-融云即时通讯云
  13. win10计算机内存,win10多大内存够用 win10系统需要多大的运行内存
  14. 摄像头与成像——做图像处理必须了解的数字成像系统原理
  15. 记录某大门户网站自动跳转不良网站,团队通宵排查病毒木马全过程
  16. 树形结构最优化问题:后根遍历
  17. solidworks动画制作教程——装配体爆炸动画
  18. css动画将图片绕着中心点旋转
  19. 【pt-px-em】有关磅、像素和em的整理
  20. AMD中国的精神-郭可尊

热门文章

  1. 【触动精灵】开发手册学习整理(一)
  2. 计算机网络上传慢,电脑上传速度慢的正确处理方法
  3. 苹果电脑开机慢怎么办
  4. 如何正确构思治具夹具的结构
  5. RGB 转换为灰度图、二值化图
  6. 基于单片机的条形码扫描系统设计
  7. 中国移动支付线下交易扩大,支付服务角逐趋热
  8. 特殊符号,emoji表情,四字节去除问题
  9. 分类计数原理与分步计数原理_分类or分步?计数原理别再傻傻分不清~
  10. 高德地图地理编码和逆地理编码,以及逆地理编码的时候如何去掉省、市、镇