org-plot.el 12.6 KB
Newer Older
Rasmus's avatar
Rasmus committed
1
;;; org-plot.el --- Support for Plotting from Org -*- lexical-binding: t; -*-
2

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 2008-2020 Free Software Foundation, Inc.
4 5 6
;;
;; Author: Eric Schulte <schulte dot eric at gmail dot com>
;; Keywords: tables, plotting
Rasmus's avatar
Rasmus committed
7
;; Homepage: https://orgmode.org
8 9 10 11 12 13 14 15 16 17 18 19 20 21
;;
;; This file is part of GNU Emacs.
;;
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
22
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
23 24 25 26 27

;;; Commentary:

;; Borrows ideas and a couple of lines of code from org-exp.el.

Rasmus's avatar
Rasmus committed
28 29
;; Thanks to the Org mailing list for testing and implementation and
;; feature suggestions
30 31

;;; Code:
Rasmus's avatar
Rasmus committed
32 33

(require 'cl-lib)
34 35 36 37 38 39 40 41 42 43 44
(require 'org)
(require 'org-table)

(declare-function gnuplot-delchar-or-maybe-eof "ext:gnuplot" (arg))
(declare-function gnuplot-mode "ext:gnuplot" ())
(declare-function gnuplot-send-buffer-to-gnuplot "ext:gnuplot" ())

(defvar org-plot/gnuplot-default-options
  '((:plot-type . 2d)
    (:with . lines)
    (:ind . 0))
45
  "Default options to gnuplot used by `org-plot/gnuplot'.")
46

47 48
(defvar org-plot-timestamp-fmt nil)

49 50 51
(defun org-plot/add-options-to-plist (p options)
  "Parse an OPTIONS line and set values in the property list P.
Returns the resulting property list."
Rasmus's avatar
Rasmus committed
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
  (when options
    (let ((op '(("type"    . :plot-type)
		("script"  . :script)
		("line"    . :line)
		("set"     . :set)
		("title"   . :title)
		("ind"     . :ind)
		("deps"    . :deps)
		("with"    . :with)
		("file"    . :file)
		("labels"  . :labels)
		("map"     . :map)
		("timeind" . :timeind)
		("timefmt" . :timefmt)))
	  (multiples '("set" "line"))
	  (regexp ":\\([\"][^\"]+?[\"]\\|[(][^)]+?[)]\\|[^ \t\n\r;,.]*\\)")
	  (start 0))
      (dolist (o op)
	(if (member (car o) multiples) ;; keys with multiple values
	    (while (string-match
		    (concat (regexp-quote (car o)) regexp)
		    options start)
	      (setq start (match-end 0))
	      (setq p (plist-put p (cdr o)
				 (cons (car (read-from-string
					     (match-string 1 options)))
				       (plist-get p (cdr o)))))
	      p)
	  (if (string-match (concat (regexp-quote (car o)) regexp)
			    options)
	      (setq p (plist-put p (cdr o)
				 (car (read-from-string
				       (match-string 1 options))))))))))
85 86 87 88 89 90 91 92 93 94
  p)

(defun org-plot/goto-nearest-table ()
  "Move the point forward to the beginning of nearest table.
Return value is the point at the beginning of the table."
  (interactive) (move-beginning-of-line 1)
  (while (not (or (org-at-table-p) (< 0 (forward-line 1)))))
  (goto-char (org-table-begin)))

(defun org-plot/collect-options (&optional params)
95
  "Collect options from an org-plot `#+Plot:' line.
96 97 98 99 100 101 102 103
Accepts an optional property list PARAMS, to which the options
will be added.  Returns the resulting property list."
  (interactive)
  (let ((line (thing-at-point 'line)))
    (if (string-match "#\\+PLOT: +\\(.*\\)$" line)
	(org-plot/add-options-to-plist params (match-string 1 line))
      params)))

104 105 106 107
(defun org-plot-quote-timestamp-field (s)
  "Convert field S from timestamp to Unix time and export to gnuplot."
  (format-time-string org-plot-timestamp-fmt (org-time-string-to-time s)))

108 109 110
(defun org-plot-quote-tsv-field (s)
  "Quote field S for export to gnuplot."
  (if (string-match org-table-number-regexp s) s
111
    (if (string-match org-ts-regexp3 s)
112
	(org-plot-quote-timestamp-field s)
113
      (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\""))))
114 115 116 117 118

(defun org-plot/gnuplot-to-data (table data-file params)
  "Export TABLE to DATA-FILE in a format readable by gnuplot.
Pass PARAMS through to `orgtbl-to-generic' when exporting TABLE."
  (with-temp-file
119
      data-file
Rasmus's avatar
Rasmus committed
120 121 122
    (setq-local org-plot-timestamp-fmt (or
					(plist-get params :timefmt)
					"%Y-%m-%d-%H:%M:%S"))
123
    (insert (orgtbl-to-generic
124 125 126 127
	     table
	     (org-combine-plists
	      '(:sep "\t" :fmt org-plot-quote-tsv-field)
	      params))))
128 129 130 131
  nil)

(defun org-plot/gnuplot-to-grid-data (table data-file params)
  "Export the data in TABLE to DATA-FILE for gnuplot.
132
This means in a format appropriate for grid plotting by gnuplot.
133
PARAMS specifies which columns of TABLE should be plotted as independent
Bastien's avatar
Bastien committed
134
and dependent variables."
135 136 137 138 139
  (interactive)
  (let* ((ind (- (plist-get params :ind) 1))
	 (deps (if (plist-member params :deps)
		   (mapcar (lambda (val) (- val 1)) (plist-get params :deps))
		 (let (collector)
Rasmus's avatar
Rasmus committed
140
		   (dotimes (col (length (nth 0 table)))
141 142
		     (setf collector (cons col collector)))
		   collector)))
143 144
	 (counter 0)
	 row-vals)
145 146 147 148 149 150 151 152 153 154 155 156 157
    (when (>= ind 0) ;; collect values of ind col
      (setf row-vals (mapcar (lambda (row) (setf counter (+ 1 counter))
			       (cons counter (nth ind row))) table)))
    (when (or deps (>= ind 0)) ;; remove non-plotting columns
      (setf deps (delq ind deps))
      (setf table (mapcar (lambda (row)
			    (dotimes (col (length row))
			      (unless (memq col deps)
				(setf (nth col row) nil)))
			    (delq nil row))
			  table)))
    ;; write table to gnuplot grid datafile format
    (with-temp-file data-file
Rasmus's avatar
Rasmus committed
158
      (let ((num-rows (length table)) (num-cols (length (nth 0 table)))
159 160 161 162 163
	    (gnuplot-row (lambda (col row value)
			   (setf col (+ 1 col)) (setf row (+ 1 row))
			   (format "%f  %f  %f\n%f  %f  %f\n"
				   col (- row 0.5) value ;; lower edge
				   col (+ row 0.5) value))) ;; upper edge
164
	    front-edge back-edge)
165 166 167 168 169 170 171 172 173 174 175 176 177 178
	(dotimes (col num-cols)
	  (dotimes (row num-rows)
	    (setf back-edge
		  (concat back-edge
			  (funcall gnuplot-row (- col 1) row
				   (string-to-number (nth col (nth row table))))))
	    (setf front-edge
		  (concat front-edge
			  (funcall gnuplot-row col row
				   (string-to-number (nth col (nth row table)))))))
	  ;; only insert once per row
	  (insert back-edge) (insert "\n") ;; back edge
	  (insert front-edge) (insert "\n") ;; front edge
	  (setf back-edge "") (setf front-edge ""))))
179 180
    row-vals))

181
(defun org-plot/gnuplot-script (data-file num-cols params &optional preface)
182
  "Write a gnuplot script to DATA-FILE respecting the options set in PARAMS.
183 184 185
NUM-COLS controls the number of columns plotted in a 2-d plot.
Optional argument PREFACE returns only option parameters in a
manner suitable for prepending to a user-specified script."
186
  (let* ((type (plist-get params :plot-type))
Rasmus's avatar
Rasmus committed
187
	 (with (if (eq type 'grid) 'pm3d (plist-get params :with)))
188 189 190 191 192 193
	 (sets (plist-get params :set))
	 (lines (plist-get params :line))
	 (map (plist-get params :map))
	 (title (plist-get params :title))
	 (file (plist-get params :file))
	 (ind (plist-get params :ind))
194 195
	 (time-ind (plist-get params :timeind))
	 (timefmt (plist-get params :timefmt))
196 197 198 199 200 201
	 (text-ind (plist-get params :textind))
	 (deps (if (plist-member params :deps) (plist-get params :deps)))
	 (col-labels (plist-get params :labels))
	 (x-labels (plist-get params :xlabels))
	 (y-labels (plist-get params :ylabels))
	 (plot-str "'%s' using %s%d%s with %s title '%s'")
Rasmus's avatar
Rasmus committed
202 203 204 205
	 (plot-cmd (pcase type
		     (`2d "plot")
		     (`3d "splot")
		     (`grid "splot")))
206
	 (script "reset")
Rasmus's avatar
Rasmus committed
207 208
	 ;; ats = add-to-script
	 (ats (lambda (line) (setf script (concat script "\n" line))))
209
	 plot-lines)
Rasmus's avatar
Rasmus committed
210
    (when file				; output file
211 212
      (funcall ats (format "set term %s" (file-name-extension file)))
      (funcall ats (format "set output '%s'" file)))
Rasmus's avatar
Rasmus committed
213 214 215 216 217 218 219 220 221 222 223
    (pcase type				; type
      (`2d ())
      (`3d (when map (funcall ats "set map")))
      (`grid (funcall ats (if map "set pm3d map" "set pm3d"))))
    (when title (funcall ats (format "set title '%s'" title))) ; title
    (mapc ats lines)					       ; line
    (dolist (el sets) (funcall ats (format "set %s" el)))      ; set
    ;; Unless specified otherwise, values are TAB separated.
    (unless (string-match-p "^set datafile separator" script)
      (funcall ats "set datafile separator \"\\t\""))
    (when x-labels			; x labels (xtics)
224 225 226 227 228
      (funcall ats
	       (format "set xtics (%s)"
		       (mapconcat (lambda (pair)
				    (format "\"%s\" %d" (cdr pair) (car pair)))
				  x-labels ", "))))
Rasmus's avatar
Rasmus committed
229
    (when y-labels			; y labels (ytics)
230 231 232 233 234
      (funcall ats
	       (format "set ytics (%s)"
		       (mapconcat (lambda (pair)
				    (format "\"%s\" %d" (cdr pair) (car pair)))
				  y-labels ", "))))
Rasmus's avatar
Rasmus committed
235
    (when time-ind			; timestamp index
236 237
      (funcall ats "set xdata time")
      (funcall ats (concat "set timefmt \""
Rasmus's avatar
Rasmus committed
238
			   (or timefmt	; timefmt passed to gnuplot
239 240
			       "%Y-%m-%d-%H:%M:%S") "\"")))
    (unless preface
Rasmus's avatar
Rasmus committed
241 242 243 244 245
      (pcase type			; plot command
	(`2d (dotimes (col num-cols)
	       (unless (and (eq type '2d)
			    (or (and ind (equal (1+ col) ind))
				(and deps (not (member (1+ col) deps)))))
246 247 248
		 (setf plot-lines
		       (cons
			(format plot-str data-file
249
				(or (and ind (> ind 0)
Rasmus's avatar
Rasmus committed
250 251 252
					 (not text-ind)
					 (format "%d:" ind)) "")
				(1+ col)
253 254
				(if text-ind (format ":xticlabel(%d)" ind) "")
				with
Rasmus's avatar
Rasmus committed
255 256
				(or (nth col col-labels)
				    (format "%d" (1+ col))))
257
			plot-lines)))))
Rasmus's avatar
Rasmus committed
258
	(`3d
259 260
	 (setq plot-lines (list (format "'%s' matrix with %s title ''"
					data-file with))))
Rasmus's avatar
Rasmus committed
261
	(`grid
262 263
	 (setq plot-lines (list (format "'%s' with %s title ''"
					data-file with)))))
264
      (funcall ats
Rasmus's avatar
Rasmus committed
265 266 267
	       (concat plot-cmd " " (mapconcat #'identity
					       (reverse plot-lines)
					       ",\\\n    "))))
268
    script))
269 270 271 272 273

;;-----------------------------------------------------------------------------
;; facade functions
;;;###autoload
(defun org-plot/gnuplot (&optional params)
274
  "Plot table using gnuplot.  Gnuplot options can be specified with PARAMS.
275 276 277 278 279 280
If not given options will be taken from the +PLOT
line directly before or after the table."
  (interactive)
  (require 'gnuplot)
  (save-window-excursion
    (delete-other-windows)
Rasmus's avatar
Rasmus committed
281
    (when (get-buffer "*gnuplot*") ; reset *gnuplot* if it already running
282
      (with-current-buffer "*gnuplot*"
Rasmus's avatar
Rasmus committed
283
	(goto-char (point-max))))
284
    (org-plot/goto-nearest-table)
Rasmus's avatar
Rasmus committed
285 286 287 288
    ;; Set default options.
    (dolist (pair org-plot/gnuplot-default-options)
      (unless (plist-member params (car pair))
	(setf params (plist-put params (car pair) (cdr pair)))))
289 290 291
    ;; collect table and table information
    (let* ((data-file (make-temp-file "org-plot"))
	   (table (org-table-to-lisp))
Rasmus's avatar
Rasmus committed
292 293 294 295 296 297 298 299 300
	   (num-cols (length (if (eq (nth 0 table) 'hline) (nth 1 table)
			       (nth 0 table)))))
      (run-with-idle-timer 0.1 nil #'delete-file data-file)
      (while (eq 'hline (car table)) (setf table (cdr table)))
      (when (eq (cadr table) 'hline)
	(setf params
	      (plist-put params :labels (nth 0 table))) ; headers to labels
	(setf table (delq 'hline (cdr table)))) ; clean non-data from table
      ;; Collect options.
301
      (save-excursion (while (and (equal 0 (forward-line -1))
302
				  (looking-at "[[:space:]]*#\\+"))
303
			(setf params (org-plot/collect-options params))))
Rasmus's avatar
Rasmus committed
304 305 306 307 308
      ;; Dump table to datafile (very different for grid).
      (pcase (plist-get params :plot-type)
	(`2d   (org-plot/gnuplot-to-data table data-file params))
	(`3d   (org-plot/gnuplot-to-data table data-file params))
	(`grid (let ((y-labels (org-plot/gnuplot-to-grid-data
309 310
				table data-file params)))
		 (when y-labels (plist-put params :ylabels y-labels)))))
Rasmus's avatar
Rasmus committed
311 312 313
      ;; Check for timestamp ind column.
      (let ((ind (1- (plist-get params :ind))))
	(when (and (>= ind 0) (eq '2d (plist-get params :plot-type)))
314 315
	  (if (= (length
		  (delq 0 (mapcar
316
			   (lambda (el)
Rasmus's avatar
Rasmus committed
317 318 319
			     (if (string-match org-ts-regexp3 el) 0 1))
			   (mapcar (lambda (row) (nth ind row)) table))))
		 0)
320
	      (plist-put params :timeind t)
Rasmus's avatar
Rasmus committed
321
	    ;; Check for text ind column.
322 323 324 325 326 327
	    (if (or (string= (plist-get params :with) "hist")
		    (> (length
			(delq 0 (mapcar
				 (lambda (el)
				   (if (string-match org-table-number-regexp el)
				       0 1))
Rasmus's avatar
Rasmus committed
328 329
				 (mapcar (lambda (row) (nth ind row)) table))))
		       0))
330
		(plist-put params :textind t)))))
Rasmus's avatar
Rasmus committed
331
      ;; Write script.
332
      (with-temp-buffer
Rasmus's avatar
Rasmus committed
333
	(if (plist-get params :script)	; user script
334 335 336 337 338
	    (progn (insert
                    (org-plot/gnuplot-script data-file num-cols params t))
                   (insert "\n")
                   (insert-file-contents (plist-get params :script))
                   (goto-char (point-min))
339
                   (while (re-search-forward "\\$datafile" nil t)
340
                     (replace-match data-file nil nil)))
Rasmus's avatar
Rasmus committed
341 342
	  (insert (org-plot/gnuplot-script data-file num-cols params)))
	;; Graph table.
343 344
	(gnuplot-mode)
	(gnuplot-send-buffer-to-gnuplot))
Rasmus's avatar
Rasmus committed
345 346
      ;; Cleanup.
      (bury-buffer (get-buffer "*gnuplot*")))))
347 348 349

(provide 'org-plot)

350 351 352 353
;; Local variables:
;; generated-autoload-file: "org-loaddefs.el"
;; End:

354
;;; org-plot.el ends here