Very Simple Plotting in Emacs

Posted on February 20, 2012

I sometimes have programs output a bunch of numbers, just one column, for example to show progress, or convergence, or something else. Then, I want that to be plotted, quickly, just to get an idea.

Here is what you can do if you use Emacs, with minimal effort:

;; Provides the plot-buffer command, a *very* simple plotting tool.
;; The command takes the file name of the current buffer, and
;; calls a gnuplot "plot" command with that file.
;; It takes the output image (in png format) and displays it at the
;; current position.
;; Feel free to change the commands, image format, or image size in the code below.
;; (C) Copyright 2012 Christian Gosch
;; This file is distributed under the terms of the GNU General Public License (GPL):

(defun plot-buffer ()
  (let* ((fn (buffer-file-name (current-buffer)))
         (tmpname (format "%s.png" (make-temp-file "gnuplot")))
         (cmds (format "set term 'png' size 680,400; set output '%s';" tmpname))
         (plot-cmd (format "%s plot '%s' w l;" cmds fn)))
    (call-process "gnuplot" nil "*Messages*" nil "-e" plot-cmd)
    (let ((im (create-image tmpname 'png)))
      (insert (format "Image file: %s\n" tmpname))
      (insert-image im))))

Save that as ~/.emacs.d/plot.el or wherever your emacs files reside, then add

(load "~/.emacs.d/plot.el")

to your Emacs startup file, usually ~/.emacs.

Load the file, then do “M-x plot-buffer”, and you should see the image inserted!

If you want to take the occasional look while a long-running process generates numbers, do “M-x auto-revert-mode”, and call “M-x plot-buffer” now and then.

Of course, you will need gnuplot to be installed on your system, and it needs to be in the system path.

This worked for me both in GNU/Linux® and Windows®.

Emacs is cool.