gnuplot 读取逗号分隔的数据文件

最后更新于:2022-04-01 07:31:51

有时,我们的数据文件中各个数据之间是用逗号作为分隔符的,比如标准的以“CSV”为后缀的那种数据文件。如果在逗号之后没有空格分隔,默认情况下gnuplot是无法直接读取的。 这时可以有两种方案,第一种是提前处理一下数据文件,比如将逗号替换为空格,随便一个文本处理软件都能很轻松的做这种替换。但是有时我们有很多这样的数据文件,每个都这样处理一下也挺麻烦的。 第二种方法就是在gnuplot中给出文件分隔符的信息,让gnuplot能够读懂我们的文件。下面将要说的就是这种方法。 比如我们有如下的文件: ~~~ -3,0.1,0.0001234098 -2.9,0.1062699256,0.0002226299 -2.8,0.1131221719,0.000393669 -2.7,0.1206272618,0.0006823281 -2.6,0.1288659794,0.0011592292 -2.5,0.1379310345,0.0019304541 -2.4,0.1479289941,0.0031511116 -2.3,0.1589825119,0.0050417603 -2.2,0.1712328767,0.0079070541 -2.1,0.1848428835,0.0121551783 -2,0.2,0.0183156389 -1.9,0.2169197397,0.0270518469 -1.8,0.2358490566,0.0391638951 -1.7,0.2570694087,0.0555762126 -1.6,0.2808988764,0.0773047404 -1.5,0.3076923077,0.1053992246 -1.4,0.3378378378,0.1408584209 -1.3,0.3717472119,0.184519524 -1.2,0.4098360656,0.2369277587 -1.1,0.4524886878,0.2981972794 -1,0.5,0.3678794412 -0.9,0.5524861878,0.4448580662 -0.8,0.6097560976,0.527292424 -0.7,0.6711409396,0.6126263942 -0.6,0.7352941176,0.6976763261 -0.5,0.8,0.7788007831 -0.4,0.8620689655,0.852143789 -0.3,0.9174311927,0.9139311853 -0.2,0.9615384615,0.9607894392 -0.1,0.9900990099,0.9900498337 0,1,1 0.1,0.9900990099,0.9900498337 0.2,0.9615384615,0.9607894392 0.3,0.9174311927,0.9139311853 0.4,0.8620689655,0.852143789 0.5,0.8,0.7788007831 0.6,0.7352941176,0.6976763261 0.7,0.6711409396,0.6126263942 0.8,0.6097560976,0.527292424 0.9,0.5524861878,0.4448580662 1,0.5,0.3678794412 1.1,0.4524886878,0.2981972794 1.2,0.4098360656,0.2369277587 1.3,0.3717472119,0.184519524 1.4,0.3378378378,0.1408584209 1.5,0.3076923077,0.1053992246 1.6,0.2808988764,0.0773047404 1.7,0.2570694087,0.0555762126 1.8,0.2358490566,0.0391638951 1.9,0.2169197397,0.0270518469 2,0.2,0.0183156389 2.1,0.1848428835,0.0121551783 2.2,0.1712328767,0.0079070541 2.3,0.1589825119,0.0050417603 2.4,0.1479289941,0.0031511116 2.5,0.1379310345,0.0019304541 2.6,0.1288659794,0.0011592292 2.7,0.1206272618,0.0006823281 2.8,0.1131221719,0.000393669 2.9,0.1062699256,0.0002226299 3,0.1,0.0001234098 ~~~ 可以看到,数据有三列,用逗号来分隔,我们下面的例子中之用到前两列。如果直接用如下命令的话得到的不是我们希望的结果。 ~~~ Plot 'sample.csv' ~~~ ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-01-24_56a423420c50e.png) gnuplot 只解析出了第一列的数据。如果我们告诉gnuplot我们的数据有两列会怎样呢? ~~~ Plot 'sample.csv' using 1:2 ~~~ gnuplot 会抱怨说: ~~~ gnuplot> plot 'sample.csv' using 1:2 ^ warning: Skipping data file with no valid points ^ x range is invalid ~~~ 正确的方法是这样的: plot 'sample.csv' using 1:2 "%lf,%lf" ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-01-24_56a423421ae87.png) 格式字符串的格式与C语言中scanf的格式字符串是类似的,实际上gnuplot最后就是用的scanf函数来读取数据。%lf表示按照 double型浮点数类型来读取。需要注意的是gnuplot的格式化字符串不支持%f。 gnuplot的格式化字符串还有很多的用法,这里就不多介绍了,有兴趣的可以参考帮助文档相关章节。
';