Data Visualization with GNU Emacs

 


 

GNU Emacs can be used for quick data visualization in combination with Gnuplot. When you have some data and you want to visualize what the correlation looks like, this command comes in handy. No need for any setup - no data file and no Gnuplot script.

The command below uses some sensible defaults for trivial cases.

  • If the first line contains string label, the same is used as a key label for the value and/or axes' names as appropriate.
  • If there's a single column of data, it is used as Y value.
  • If there's more than one column, first column is used as X value and other columns are plotted along Y-axis.
  • Takes care of comma or whitespace separator.

Note: The latest version of the code is available at the end of the post.

Options available in latest version

 

- Install gnuplot executable and gnuplot Elisp package.

- Evaluate the defun (C-M-x).

- Select a data range using rectangle command copy-rectangle-as-kill (C-x r M-w).

- Run M-x  gnuplot-rectangle. This opens the graph in a new window for easier interaction. Use C-q to exit.

- Run C-u M-x  gnuplot-rectangle to specify title and style (added in updated version).

(defun gnuplot-rectangle (&optional title style)
  (interactive)
  (let* ((name (make-temp-file "plot"))
         (buf (find-file name))
         xlabel ylabel cols header n)
    (with-current-buffer buf
      (setq cols (split-string (car killed-rectangle)))
      (when (string-match-p "^[a-zA-Z]" (car cols))
        (setq header cols)
        (pop killed-rectangle))
      (setq n (length header))
      (pcase n
        (1 (setq ylabel (nth 1 header)))
        (2 (setq xlabel (nth 0 header)
                 ylabel (nth 1 header)))
        (_ (setq xlabel (nth 0 header))))
      (yank-rectangle)
      (save-buffer))

    (setq style (or style "line"))
    (with-temp-buffer
      (insert "set title  '" (or title "Title") "'\n")
      (insert "set xlabel '" (or xlabel "x-axis") "'\n")
      (insert "set ylabel '" (or ylabel "y-axis") "'\n")
      (insert "plot '" name "'")
      (setq n (length cols))
      (dotimes (i (1- n))
        (if (> n 1) (insert " using 1:" (number-to-string (+ i 2))))
        (if (< i n) (insert " with " style))
        (if (> n 2)
            (insert " title '" (nth (+ i 1) header) "'")
          (insert " notitle"))
        (if (> i 0) (insert ",")))
      (if (= 1 n) (insert " using 1 with " style " notitle"))
      (newline)
      (gnuplot-mode)
      (gnuplot-send-buffer-to-gnuplot))

    ;; Cleanup
    (kill-buffer buf)
    ;; (delete-file name)
    )) 

 

Bar graph


Time series


Scatter plot


Pie chart


Live Preview

Use M-x gnuplot-preview to generate live preview of supported graph types.


Code

 

Comments

Popular posts from this blog

GNU Emacs as a Comic Book Reader

Mozilla Readability in GNU Emacs