【发布时间】:2013-05-31 15:55:59
【问题描述】:
我在文件中有一个数据,我想使用 gnuplot 进行绘图。在文件中,有 3 个数据集由两个空行分隔,以便 gnuplot 可以通过“索引”区分数据集。我可以通过“plot”命令的“index”选项分别绘制三个数据集。 但是,我不确定如何绘制所有三个数据集的第二列总和的数据?
注意:所有三个数据集都有相同的 x 数据,即第一列
【问题讨论】:
我在文件中有一个数据,我想使用 gnuplot 进行绘图。在文件中,有 3 个数据集由两个空行分隔,以便 gnuplot 可以通过“索引”区分数据集。我可以通过“plot”命令的“index”选项分别绘制三个数据集。 但是,我不确定如何绘制所有三个数据集的第二列总和的数据?
注意:所有三个数据集都有相同的 x 数据,即第一列
【问题讨论】:
要做到这一点,最简单的方法是更改文件格式。 Gnuplot 可以很好地处理列。由于您共享 x 数据,您可以将文件格式更改为有四列(假设您只是在绘制 (x,y) 数据):
<x data> <y1 data> <y2 data> <y3 data>
并使用类似的命令
plot 'data.dat' using 1:2 title 'data 1', \
'' u 1:3 t 'data 2', \
'' u 1:4 t 'data 3', \
'' u 1:($2+$3+$4) t 'sum of datas'
using 列规范中括号内的美元符号允许您对列数据添加/减去/执行其他功能。
这样你的数据文件也会更小,因为你不会重复 x 数据。
【讨论】:
set table 提取一个新数据集。但这会导致中间文件的工作/数据流更加费力......
@Youjun Hu,永远不要说“没有办法”用 gnuplot 做某事。那里的大多数情况是仅使用 gnuplot 的方法,有时可能不明显或有时有点麻烦。
数据: SO16861334.dat
1 11
2 12
3 13
4 14
1 21
2 22
3 23
4 24
1 31
2 32
3 33
4 34
代码 1:(适用于 gnuplot 4.6.0,需要对 >=4.6.5 进行一些调整)
在 gnuplot 4.6.0(OP 提出问题时的版本)中没有数据块,也没有 plot ... with table。下面的示例仅适用于 3 个子数据集,但可以适用于其他数字。但是,使用这种方法将难以处理任意数量的子数据集。
### calculate sum from 3 different (sub)datasets, gnuplot 4.6.0
reset
FILE = "SO16861334.dat"
stats FILE u 0 nooutput
N = int(STATS_records/STATS_blocks) # get number of lines per subblock
set table FILE."2"
plot FILE u 1:2
set table FILE."3"
x1=x2=y1=y2=NaN
myValueX(col) = (x0=x1,x1=x2,x2=column(col), r=int($0-2)/N, r<1 ? x0 : r<2 ? x1 : x2)
myValueY(col) = (y0=y1,y1=y2,y2=column(col), r<1 ? y0 : r<2 ? y1 : y2)
plot FILE."2" u (myValueX(1)):(myValueY(2))
unset table
set key top left
set offset graph 0.1, graph 0.1, graph 0.2, graph 0.1
plot for [i=0:2] FILE u 1:2 index i w lp pt 7 lc i+1 ti sprintf("index %d",i), \
FILE."3" u 1:2 every ::2 smooth freq w lp pt 7 lc rgb "magenta" ti "sum"
### end of code
代码 2:(适用于 gnuplot>=5.0.0)
此代码适用于任意数量的子数据集。
### calculate sum from 3 different (sub)datasets, gnuplot>=5.0.0
reset
FILE = "SO16861334.dat"
set table $Data2
plot FILE u 1:2 w table
unset table
set key top left
set offset graph 0.1, graph 0.1, graph 0.2, graph 0.1
set colorsequence classic
plot for [i=0:2] FILE u 1:2 index i w lp pt 7 lc i+1 ti sprintf("index %d",i), \
$Data2 u 1:2 smooth freq w lp pt 7 lc rgb "magenta" ti "sum"
### end of code
结果:(使用 gnuplot 4.6.0 的 Code1 和使用 gnuplot 5.0.0 的 Code2 的结果相同)
【讨论】:
$Data2 with table 您将删除空行。当使用选项smooth freq 绘制$Data2 时,您基本上是在创建一个直方图,其中 x 值作为 bin 并对 y 值求和。检查help smooth。