org-plot.el 13 KB

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