org-plot.el 13 KB

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