问题
I have the following code, which plots 4 lines:
plot for [i=1:4] \
path_to_file using 1:(column(i)) , \
I also want to plot 8 horizontal lines on this graph, the values of which come from mydata.txt.
I have seen, from the answer to Gnuplot: How to load and display single numeric value from data file, that I can use the stats command to access the constant values I am interested in. I think I can access the cell (row, col) as follows:
stats 'mydata.txt' every ::row::row using col nooutput
value = int(STATS_min)
But their location is a function of i. So, inside the plot command, I want to add something like:
for [i=1:4] \
stats 'mydata.txt' every ::(1+i*10)::(1+i*10) using 1 nooutput
mean = int(STATS_min)
stats 'mydata.txt' every ::(1+i*10)::(1+i*10) using 2 nooutput
SE = int(STATS_min)
upper = mean + 2 * SE
lower = mean - 2 * SE
and then plot upper and lower, as horizontal lines on the graph, above.
I think I can plot them separately by typing plot upper, lower
but how do I plot them on the graph, above, for all i?
Thank you.
回答1:
You can create an array and store the values in it, then using an index that refers to the value's position in the array you can access it inside a loop.
You can create the array as follows:
array=""
do for [i=1:4] {
val = i / 9.
array = sprintf("%s %g",array,val)
}
where I have stored 4 values: 1/9, 2/9, 3/9 and 4/9. In your case you would run stats
and store your upper
and/or lower
variables. You can check what the array looks like in this way:
gnuplot> print array
0.111111 0.222222 0.333333 0.444444
For plotting, you can access the different elements in the array using word(array,i)
, where i
refers to the position. Since the array is a string, you need to convert it to float, which can be done multiplying by 1.
:
plot for [i=1:4] 1.*word(array,i)

If you have values stored in a data file, you can process it with awk
or even with gnuplot:
array = ""
plot for [i=1:4] "data" every ::i::i u (array=sprintf("%s %g",array,$1), 1/0), \
for [i=1:4] 1.*word(array,i)
The first plot
instance creates the array from the first column data entries without plotting the points (the 1/0
option tells gnuplot to ignore them, so expect warning messages) and the second plot
instance uses the values stored in array
as variables (hence as horizontal lines in this case). Note that every
takes 0 as the first entry, so [i=1:4]
runs from the second through to the fifth lines of the file.
来源:https://stackoverflow.com/questions/26818550/can-i-calculate-something-inside-a-for-loop-and-then-plot-those-values-on-the-sa