org-plot.el 13 KB

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