如何调整gnuplot脚本第32行,解决字符串格式打印数值报错?
解决gnuplot脚本sprintf格式报错问题
错误原因
报错f_sprintf: attempt to print numeric value with string format的核心原因有两点:
- 新版本gnuplot对字符串类型校验更严格,原脚本中通过
strcol(4)获取的带引号列标题,被隐式解析为非纯字符串类型,导致sprintf("%s.emf",s)的字符串格式符接收了不匹配的参数。 - 路径拼接语法错误:
outputDirs.myFileOut(s)不是gnuplot的字符串拼接方式,会触发意外的类型解析。
修改后的完整脚本
###subblocks to free energy diagrams### set terminal emf font "Sans Bold,25" enhanced set terminal emf size 640,530 makebold(text) = sprintf("{/:Bold %s}", text) set border 15 front lt black linewidth 3.000 dashtype solid set xlabel "Reaction Coordinate" set xrange [-0.2:5.2] set xtics nomirror scale 0 set ylabel "Free Energy (eV)" set ylabel offset character 4.5,-3.0,0 font "Sans Bold,25" enhanced set xlabel offset character 0,0.6,0 font "Sans Bold,25" enhanced set yrange[-5:0.4] set ytics in nomirror font "Sans Bold,25" enhanced set key noautotitle samplen 2 set key enhanced set key at 2.1,-3,0 set errorbars 0 dx = 0.2 set pointintervalbox 0.0 myFileOut(s) = sprintf("%s.emf", string(s)) # 强制转换为字符串类型 myTitle(s) = sprintf("%s", string(s)) inputFiles = '/Desktop/test-2.dat' outputDirs = "/Desktop/test-2" do for [i=0:2] { # 提取不带双引号的第4列标题字符串 stats inputFiles index i every ::::0 u (col4=strcol(4), s=col4[2:strlen(col4)-1], 0) nooutput # 正确拼接输出路径:目录 + 斜杠 + 文件名 set output outputDirs . "/" . myFileOut(s) set title myTitle(s) offset 0,-0.93, 0 plot inputFiles index i u 0:2:(dx):xtic(makebold(strcol(1))) w xerr lc "blue" lw 3 ps 0 ti columnheader(2), \ "" index i u 0:3:(dx) w xerr lc "red" lw 3 ps 0 ti columnheader(3), \ x1=y1=NaN "" index i u (x0=x1,x1=$0,x0-1+dx):(y0=y1,y1=$2,y0):(1-2*dx):(y1-y0) w vec dt 4 lc "blue" nohead, \ x1=y1=NaN "" index i u (x0=x1,x1=$0,x0-1+dx):(y0=y1,y1=$3,y0):(1-2*dx):(y1-y0) w vec dt 4 lc "red" nohead } set output ### end of script
关键修改点说明
- 提取纯净字符串:通过
col4[2:strlen(col4)-1]截取列标题中双引号内的内容,避免引号导致的类型解析问题。 - 强制类型转换:在
sprintf中用string(s)确保参数为纯字符串,适配新版本gnuplot的类型校验规则。 - 修复路径拼接:用gnuplot标准的字符串连接符
.,将目录路径、斜杠、文件名正确拼接,避免路径解析错误。
内容的提问来源于stack exchange,提问作者Courtney Brea
相关产品推荐
相关产品推荐

