org-plot.el 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. ;;; org-plot.el --- Support for Plotting from Org -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2008-2020 Free Software Foundation, Inc.
  3. ;;
  4. ;; Author: Eric Schulte <schulte dot eric at gmail dot com>
  5. ;; Keywords: tables, plotting
  6. ;; Homepage: https://orgmode.org
  7. ;;
  8. ;; This file is part of GNU Emacs.
  9. ;;
  10. ;; GNU Emacs is free software: you can redistribute it and/or modify
  11. ;; it under the terms of the GNU General Public License as published by
  12. ;; the Free Software Foundation, either version 3 of the License, or
  13. ;; (at your option) any later version.
  14. ;; GNU Emacs is distributed in the hope that it will be useful,
  15. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. ;; GNU General Public License for more details.
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  20. ;;; Commentary:
  21. ;; Borrows ideas and a couple of lines of code from org-exp.el.
  22. ;; Thanks to the Org mailing list for testing and implementation and
  23. ;; feature suggestions
  24. ;;; Code:
  25. (require 'cl-lib)
  26. (require 'org)
  27. (require 'org-table)
  28. (declare-function gnuplot-delchar-or-maybe-eof "ext:gnuplot" (arg))
  29. (declare-function gnuplot-mode "ext:gnuplot" ())
  30. (declare-function gnuplot-send-buffer-to-gnuplot "ext:gnuplot" ())
  31. (defvar org-plot/gnuplot-default-options
  32. '((:plot-type . 2d)
  33. (:with . lines)
  34. (:ind . 0))
  35. "Default options to gnuplot used by `org-plot/gnuplot'.")
  36. (defvar org-plot-timestamp-fmt nil)
  37. (defun org-plot/add-options-to-plist (p options)
  38. "Parse an OPTIONS line and set values in the property list P.
  39. Returns the resulting property list."
  40. (when options
  41. (let ((op '(("type" . :plot-type)
  42. ("script" . :script)
  43. ("line" . :line)
  44. ("set" . :set)
  45. ("title" . :title)
  46. ("ind" . :ind)
  47. ("deps" . :deps)
  48. ("with" . :with)
  49. ("file" . :file)
  50. ("labels" . :labels)
  51. ("map" . :map)
  52. ("timeind" . :timeind)
  53. ("timefmt" . :timefmt)))
  54. (multiples '("set" "line"))
  55. (regexp ":\\([\"][^\"]+?[\"]\\|[(][^)]+?[)]\\|[^ \t\n\r;,.]*\\)")
  56. (start 0))
  57. (dolist (o op)
  58. (if (member (car o) multiples) ;; keys with multiple values
  59. (while (string-match
  60. (concat (regexp-quote (car o)) regexp)
  61. options start)
  62. (setq start (match-end 0))
  63. (setq p (plist-put p (cdr o)
  64. (cons (car (read-from-string
  65. (match-string 1 options)))
  66. (plist-get p (cdr o)))))
  67. p)
  68. (if (string-match (concat (regexp-quote (car o)) regexp)
  69. options)
  70. (setq p (plist-put p (cdr o)
  71. (car (read-from-string
  72. (match-string 1 options))))))))))
  73. p)
  74. (defun org-plot/goto-nearest-table ()
  75. "Move the point forward to the beginning of nearest table.
  76. Return value is the point at the beginning of the table."
  77. (interactive) (move-beginning-of-line 1)
  78. (while (not (or (org-at-table-p) (< 0 (forward-line 1)))))
  79. (goto-char (org-table-begin)))
  80. (defun org-plot/collect-options (&optional params)
  81. "Collect options from an org-plot `#+Plot:' line.
  82. Accepts an optional property list PARAMS, to which the options
  83. will be added. Returns the resulting property list."
  84. (interactive)
  85. (let ((line (thing-at-point 'line)))
  86. (if (string-match "#\\+PLOT: +\\(.*\\)$" line)
  87. (org-plot/add-options-to-plist params (match-string 1 line))
  88. params)))
  89. (defun org-plot-quote-timestamp-field (s)
  90. "Convert field S from timestamp to Unix time and export to gnuplot."
  91. (format-time-string org-plot-timestamp-fmt (org-time-string-to-time s)))
  92. (defun org-plot-quote-tsv-field (s)
  93. "Quote field S for export to gnuplot."
  94. (if (string-match org-table-number-regexp s) s
  95. (if (string-match org-ts-regexp3 s)
  96. (org-plot-quote-timestamp-field s)
  97. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\""))))
  98. (defun org-plot/gnuplot-to-data (table data-file params)
  99. "Export TABLE to DATA-FILE in a format readable by gnuplot.
  100. Pass PARAMS through to `orgtbl-to-generic' when exporting TABLE."
  101. (with-temp-file
  102. data-file
  103. (setq-local org-plot-timestamp-fmt (or
  104. (plist-get params :timefmt)
  105. "%Y-%m-%d-%H:%M:%S"))
  106. (insert (orgtbl-to-generic
  107. table
  108. (org-combine-plists
  109. '(:sep "\t" :fmt org-plot-quote-tsv-field)
  110. params))))
  111. nil)
  112. (defun org-plot/gnuplot-to-grid-data (table data-file params)
  113. "Export the data in TABLE to DATA-FILE for gnuplot.
  114. This means in a format appropriate for grid plotting by gnuplot.
  115. PARAMS specifies which columns of TABLE should be plotted as independent
  116. and dependent variables."
  117. (interactive)
  118. (let* ((ind (- (plist-get params :ind) 1))
  119. (deps (if (plist-member params :deps)
  120. (mapcar (lambda (val) (- val 1)) (plist-get params :deps))
  121. (let (collector)
  122. (dotimes (col (length (nth 0 table)))
  123. (setf collector (cons col collector)))
  124. collector)))
  125. (counter 0)
  126. row-vals)
  127. (when (>= ind 0) ;; collect values of ind col
  128. (setf row-vals (mapcar (lambda (row) (setf counter (+ 1 counter))
  129. (cons counter (nth ind row)))
  130. table)))
  131. (when (or deps (>= ind 0)) ;; remove non-plotting columns
  132. (setf deps (delq ind deps))
  133. (setf table (mapcar (lambda (row)
  134. (dotimes (col (length row))
  135. (unless (memq col deps)
  136. (setf (nth col row) nil)))
  137. (delq nil row))
  138. table)))
  139. ;; write table to gnuplot grid datafile format
  140. (with-temp-file data-file
  141. (let ((num-rows (length table)) (num-cols (length (nth 0 table)))
  142. (gnuplot-row (lambda (col row value)
  143. (setf col (+ 1 col)) (setf row (+ 1 row))
  144. (format "%f %f %f\n%f %f %f\n"
  145. col (- row 0.5) value ;; lower edge
  146. col (+ row 0.5) value))) ;; upper edge
  147. front-edge back-edge)
  148. (dotimes (col num-cols)
  149. (dotimes (row num-rows)
  150. (setf back-edge
  151. (concat back-edge
  152. (funcall gnuplot-row (- col 1) row
  153. (string-to-number (nth col (nth row table))))))
  154. (setf front-edge
  155. (concat front-edge
  156. (funcall gnuplot-row col row
  157. (string-to-number (nth col (nth row table)))))))
  158. ;; only insert once per row
  159. (insert back-edge) (insert "\n") ;; back edge
  160. (insert front-edge) (insert "\n") ;; front edge
  161. (setf back-edge "") (setf front-edge ""))))
  162. row-vals))
  163. (defun org-plot/gnuplot-script (data-file num-cols params &optional preface)
  164. "Write a gnuplot script to DATA-FILE respecting the options set in PARAMS.
  165. NUM-COLS controls the number of columns plotted in a 2-d plot.
  166. Optional argument PREFACE returns only option parameters in a
  167. manner suitable for prepending to a user-specified script."
  168. (let* ((type (plist-get params :plot-type))
  169. (with (if (eq type 'grid) 'pm3d (plist-get params :with)))
  170. (sets (plist-get params :set))
  171. (lines (plist-get params :line))
  172. (map (plist-get params :map))
  173. (title (plist-get params :title))
  174. (file (plist-get params :file))
  175. (ind (plist-get params :ind))
  176. (time-ind (plist-get params :timeind))
  177. (timefmt (plist-get params :timefmt))
  178. (text-ind (plist-get params :textind))
  179. (deps (if (plist-member params :deps) (plist-get params :deps)))
  180. (col-labels (plist-get params :labels))
  181. (x-labels (plist-get params :xlabels))
  182. (y-labels (plist-get params :ylabels))
  183. (plot-str "'%s' using %s%d%s with %s title '%s'")
  184. (plot-cmd (pcase type
  185. (`2d "plot")
  186. (`3d "splot")
  187. (`grid "splot")))
  188. (script "reset")
  189. ;; ats = add-to-script
  190. (ats (lambda (line) (setf script (concat script "\n" line))))
  191. plot-lines)
  192. (when file ; output file
  193. (funcall ats (format "set term %s" (file-name-extension file)))
  194. (funcall ats (format "set output '%s'" file)))
  195. (pcase type ; type
  196. (`2d ())
  197. (`3d (when map (funcall ats "set map")))
  198. (`grid (funcall ats (if map "set pm3d map" "set pm3d"))))
  199. (when title (funcall ats (format "set title '%s'" title))) ; title
  200. (mapc ats lines) ; line
  201. (dolist (el sets) (funcall ats (format "set %s" el))) ; set
  202. ;; Unless specified otherwise, values are TAB separated.
  203. (unless (string-match-p "^set datafile separator" script)
  204. (funcall ats "set datafile separator \"\\t\""))
  205. (when x-labels ; x labels (xtics)
  206. (funcall ats
  207. (format "set xtics (%s)"
  208. (mapconcat (lambda (pair)
  209. (format "\"%s\" %d" (cdr pair) (car pair)))
  210. x-labels ", "))))
  211. (when y-labels ; y labels (ytics)
  212. (funcall ats
  213. (format "set ytics (%s)"
  214. (mapconcat (lambda (pair)
  215. (format "\"%s\" %d" (cdr pair) (car pair)))
  216. y-labels ", "))))
  217. (when time-ind ; timestamp index
  218. (funcall ats "set xdata time")
  219. (funcall ats (concat "set timefmt \""
  220. (or timefmt ; timefmt passed to gnuplot
  221. "%Y-%m-%d-%H:%M:%S") "\"")))
  222. (unless preface
  223. (pcase type ; plot command
  224. (`2d (dotimes (col num-cols)
  225. (unless (and (eq type '2d)
  226. (or (and ind (equal (1+ col) ind))
  227. (and deps (not (member (1+ col) deps)))))
  228. (setf plot-lines
  229. (cons
  230. (format plot-str data-file
  231. (or (and ind (> ind 0)
  232. (not text-ind)
  233. (format "%d:" ind)) "")
  234. (1+ col)
  235. (if text-ind (format ":xticlabel(%d)" ind) "")
  236. with
  237. (or (nth col col-labels)
  238. (format "%d" (1+ col))))
  239. plot-lines)))))
  240. (`3d
  241. (setq plot-lines (list (format "'%s' matrix with %s title ''"
  242. data-file with))))
  243. (`grid
  244. (setq plot-lines (list (format "'%s' with %s title ''"
  245. data-file with)))))
  246. (funcall ats
  247. (concat plot-cmd " " (mapconcat #'identity
  248. (reverse plot-lines)
  249. ",\\\n "))))
  250. script))
  251. ;;-----------------------------------------------------------------------------
  252. ;; facade functions
  253. ;;;###autoload
  254. (defun org-plot/gnuplot (&optional params)
  255. "Plot table using gnuplot. Gnuplot options can be specified with PARAMS.
  256. If not given options will be taken from the +PLOT
  257. line directly before or after the table."
  258. (interactive)
  259. (require 'gnuplot)
  260. (save-window-excursion
  261. (delete-other-windows)
  262. (when (get-buffer "*gnuplot*") ; reset *gnuplot* if it already running
  263. (with-current-buffer "*gnuplot*"
  264. (goto-char (point-max))))
  265. (org-plot/goto-nearest-table)
  266. ;; Set default options.
  267. (dolist (pair org-plot/gnuplot-default-options)
  268. (unless (plist-member params (car pair))
  269. (setf params (plist-put params (car pair) (cdr pair)))))
  270. ;; collect table and table information
  271. (let* ((data-file (make-temp-file "org-plot"))
  272. (table (org-table-collapse-header (org-table-to-lisp)))
  273. (num-cols (length (car table))))
  274. (run-with-idle-timer 0.1 nil #'delete-file data-file)
  275. (when (eq (cadr table) 'hline)
  276. (setf params
  277. (plist-put params :labels (car table))) ; headers to labels
  278. (setf table (delq 'hline (cdr table)))) ; clean non-data from table
  279. ;; Collect options.
  280. (save-excursion (while (and (equal 0 (forward-line -1))
  281. (looking-at "[[:space:]]*#\\+"))
  282. (setf params (org-plot/collect-options params))))
  283. ;; Dump table to datafile (very different for grid).
  284. (pcase (plist-get params :plot-type)
  285. (`2d (org-plot/gnuplot-to-data table data-file params))
  286. (`3d (org-plot/gnuplot-to-data table data-file params))
  287. (`grid (let ((y-labels (org-plot/gnuplot-to-grid-data
  288. table data-file params)))
  289. (when y-labels (plist-put params :ylabels y-labels)))))
  290. ;; Check type of ind column (timestamp? text?)
  291. (when (eq `2d (plist-get params :plot-type))
  292. (let* ((ind (1- (plist-get params :ind)))
  293. (ind-column (mapcar (lambda (row) (nth ind row)) table)))
  294. (cond ((< ind 0) nil) ; ind is implicit
  295. ((cl-every (lambda (el)
  296. (string-match org-ts-regexp3 el))
  297. ind-column)
  298. (plist-put params :timeind t)) ; ind holds timestamps
  299. ((or (string= (plist-get params :with) "hist")
  300. (cl-notevery (lambda (el)
  301. (string-match org-table-number-regexp el))
  302. ind-column))
  303. (plist-put params :textind t))))) ; ind holds text
  304. ;; Write script.
  305. (with-temp-buffer
  306. (if (plist-get params :script) ; user script
  307. (progn (insert
  308. (org-plot/gnuplot-script data-file num-cols params t))
  309. (insert "\n")
  310. (insert-file-contents (plist-get params :script))
  311. (goto-char (point-min))
  312. (while (re-search-forward "\\$datafile" nil t)
  313. (replace-match data-file nil nil)))
  314. (insert (org-plot/gnuplot-script data-file num-cols params)))
  315. ;; Graph table.
  316. (gnuplot-mode)
  317. (gnuplot-send-buffer-to-gnuplot))
  318. ;; Cleanup.
  319. (bury-buffer (get-buffer "*gnuplot*")))))
  320. (provide 'org-plot)
  321. ;; Local variables:
  322. ;; generated-autoload-file: "org-loaddefs.el"
  323. ;; End:
  324. ;;; org-plot.el ends here