Saturday, January 26, 2013

Real-time plot updates using Gnuplot

Sometimes it's very convenient to see real time updates of your gnuplot graphs, for example if you're doing Monte Carlo simulations or if you have are monitoring stocks. Below I'll show you the way I do it, by only using gnuplot commands.

First, create a gnuplot configuration file called 'loop.plt', containing:

pause 2
replot
reread
Let's assume we have already given gnuplot the commands to plot something. What this piece of configuration file then does, is wait two seconds, then replot and then reread the loop.plt file. This will cause these three commands to be executed in an infinite loop. Reread is a very useful command. You can read more about it here.

Now, how do we give the first plot command? Well, there are various options. You could for example add the plot command to the  'loop.plt' file (which makes it less portable), but I like to give the instructions through the command line:
gnuplot -persist -e "plot 'data.dat'" loop.plt
where data.dat is a file that is continuously updated by some process. The nice thing about this is that you can recycle the 'loop.plt' without making any changes to it.

Passing a configuration file

If you have a lot of settings, a better alternative is to let the loop configuration file load your own configuration file. We make the following adjustments:

load config
pause 2
replot
reread
and we call gnuplot with:

gnuplot -persist -e "config='config.plt'" loop.plt
Which sets the variable config to your own configuration file. Using this method we have the option to just call gnuplot 'config.plt' to draw the plot once, or use the above command to keep refreshing without having to change any of the files. If you want to have even more control, you could also make the pause time a variable. See you next time!