Can I calculate something inside a for loop and then plot those values on the same graph?

白昼怎懂夜的黑 提交于 2020-01-03 04:53:21

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!