org-plot.el 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  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. ("min" . :ymin)
  56. ("max" . :ymax)
  57. ("ymin" . :ymin)
  58. ("xmax" . :xmax)
  59. ("ticks" . :ticks)
  60. ("trans" . :transpose)
  61. ("transpose" . :transpose)))
  62. (multiples '("set" "line"))
  63. (regexp ":\\([\"][^\"]+?[\"]\\|[(][^)]+?[)]\\|[^ \t\n\r;,.]*\\)")
  64. (start 0))
  65. (dolist (o op)
  66. (if (member (car o) multiples) ;; keys with multiple values
  67. (while (string-match
  68. (concat (regexp-quote (car o)) regexp)
  69. options start)
  70. (setq start (match-end 0))
  71. (setq p (plist-put p (cdr o)
  72. (cons (car (read-from-string
  73. (match-string 1 options)))
  74. (plist-get p (cdr o)))))
  75. p)
  76. (if (string-match (concat (regexp-quote (car o)) regexp)
  77. options)
  78. (setq p (plist-put p (cdr o)
  79. (car (read-from-string
  80. (match-string 1 options))))))))))
  81. p)
  82. (defun org-plot/goto-nearest-table ()
  83. "Move the point forward to the beginning of nearest table.
  84. Return value is the point at the beginning of the table."
  85. (interactive) (move-beginning-of-line 1)
  86. (while (not (or (org-at-table-p) (< 0 (forward-line 1)))))
  87. (goto-char (org-table-begin)))
  88. (defun org-plot/collect-options (&optional params)
  89. "Collect options from an org-plot `#+Plot:' line.
  90. Accepts an optional property list PARAMS, to which the options
  91. will be added. Returns the resulting property list."
  92. (interactive)
  93. (let ((line (thing-at-point 'line)))
  94. (if (string-match "#\\+PLOT: +\\(.*\\)$" line)
  95. (org-plot/add-options-to-plist params (match-string 1 line))
  96. params)))
  97. (defun org-plot-quote-timestamp-field (s)
  98. "Convert field S from timestamp to Unix time and export to gnuplot."
  99. (format-time-string org-plot-timestamp-fmt (org-time-string-to-time s)))
  100. (defun org-plot-quote-tsv-field (s)
  101. "Quote field S for export to gnuplot."
  102. (if (string-match org-table-number-regexp s) s
  103. (if (string-match org-ts-regexp3 s)
  104. (org-plot-quote-timestamp-field s)
  105. (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\""))))
  106. (defun org-plot/gnuplot-to-data (table data-file params)
  107. "Export TABLE to DATA-FILE in a format readable by gnuplot.
  108. Pass PARAMS through to `orgtbl-to-generic' when exporting TABLE."
  109. (with-temp-file
  110. data-file
  111. (setq-local org-plot-timestamp-fmt (or
  112. (plist-get params :timefmt)
  113. "%Y-%m-%d-%H:%M:%S"))
  114. (insert (orgtbl-to-generic
  115. table
  116. (org-combine-plists
  117. '(:sep "\t" :fmt org-plot-quote-tsv-field)
  118. params))))
  119. nil)
  120. (defun org-plot/gnuplot-to-grid-data (table data-file params)
  121. "Export the data in TABLE to DATA-FILE for gnuplot.
  122. This means in a format appropriate for grid plotting by gnuplot.
  123. PARAMS specifies which columns of TABLE should be plotted as independent
  124. and dependent variables."
  125. (interactive)
  126. (let* ((ind (- (plist-get params :ind) 1))
  127. (deps (if (plist-member params :deps)
  128. (mapcar (lambda (val) (- val 1)) (plist-get params :deps))
  129. (let (collector)
  130. (dotimes (col (length (nth 0 table)))
  131. (setf collector (cons col collector)))
  132. collector)))
  133. (counter 0)
  134. row-vals)
  135. (when (>= ind 0) ;; collect values of ind col
  136. (setf row-vals (mapcar (lambda (row) (setf counter (+ 1 counter))
  137. (cons counter (nth ind row)))
  138. table)))
  139. (when (or deps (>= ind 0)) ;; remove non-plotting columns
  140. (setf deps (delq ind deps))
  141. (setf table (mapcar (lambda (row)
  142. (dotimes (col (length row))
  143. (unless (memq col deps)
  144. (setf (nth col row) nil)))
  145. (delq nil row))
  146. table)))
  147. ;; write table to gnuplot grid datafile format
  148. (with-temp-file data-file
  149. (let ((num-rows (length table)) (num-cols (length (nth 0 table)))
  150. (gnuplot-row (lambda (col row value)
  151. (setf col (+ 1 col)) (setf row (+ 1 row))
  152. (format "%f %f %f\n%f %f %f\n"
  153. col (- row 0.5) value ;; lower edge
  154. col (+ row 0.5) value))) ;; upper edge
  155. front-edge back-edge)
  156. (dotimes (col num-cols)
  157. (dotimes (row num-rows)
  158. (setf back-edge
  159. (concat back-edge
  160. (funcall gnuplot-row (- col 1) row
  161. (string-to-number (nth col (nth row table))))))
  162. (setf front-edge
  163. (concat front-edge
  164. (funcall gnuplot-row col row
  165. (string-to-number (nth col (nth row table)))))))
  166. ;; only insert once per row
  167. (insert back-edge) (insert "\n") ;; back edge
  168. (insert front-edge) (insert "\n") ;; front edge
  169. (setf back-edge "") (setf front-edge ""))))
  170. row-vals))
  171. (defun org--plot/values-stats (nums &optional hard-min hard-max)
  172. "From a list of NUMS return a plist containing some rudamentry statistics on the
  173. values, namely regarding the range."
  174. (let* ((minimum (or hard-min (apply #'min nums)))
  175. (maximum (or hard-max (apply #'max nums)))
  176. (range (- maximum minimum))
  177. (rangeOrder (ceiling (- 1 (log10 range))))
  178. (range-factor (expt 10 rangeOrder))
  179. (nice-min (/ (float (floor (* minimum range-factor))) range-factor))
  180. (nice-max (/ (float (ceiling (* maximum range-factor))) range-factor)))
  181. `(:min ,minimum :max ,maximum :range ,range
  182. :range-factor ,range-factor
  183. :nice-min ,nice-min :nice-max ,nice-max :nice-range ,(- nice-max nice-min))))
  184. (defun org--plot/sensible-tick-num (table &optional hard-min hard-max)
  185. "From a the values in a TABLE of data, attempt to guess an appropriate number of ticks."
  186. (let* ((row-data
  187. (mapcar (lambda (row) (org--plot/values-stats
  188. (mapcar #'string-to-number (cdr row))
  189. hard-min
  190. hard-max)) table))
  191. (row-normalised-ranges (mapcar (lambda (r-data)
  192. (let ((val (round (*
  193. (plist-get r-data :range-factor)
  194. (plist-get r-data :nice-range)))))
  195. (if (= (% val 10) 0) (/ val 10) val)))
  196. row-data))
  197. (range-prime-decomposition (mapcar #'org--plot/prime-factors row-normalised-ranges))
  198. (weighted-factors (sort (apply #'org--plot/merge-alists #'+ 0
  199. (mapcar (lambda (factors) (org--plot/item-frequencies factors t))
  200. range-prime-decomposition))
  201. (lambda (a b) (> (cdr a) (cdr b))))))
  202. (apply #'* (org--plot/nice-frequency-pick weighted-factors))))
  203. (defun org--plot/nice-frequency-pick (frequencies)
  204. "From a list of frequences, try to sensibly pick a sample of the most frequent."
  205. ;; TODO this mosly works decently, but counld do with some tweaking to work more consistently.
  206. (case (length frequencies)
  207. (1 (list (car (nth 0 frequencies))))
  208. (2 (if (<= 3 (/ (cdr (nth 0 frequencies))
  209. (cdr (nth 1 frequencies))))
  210. (make-list 2
  211. (car (nth 0 frequencies)))
  212. (list (car (nth 0 frequencies))
  213. (car (nth 1 frequencies)))))
  214. (t
  215. (let* ((total-count (apply #'+ (mapcar #'cdr frequencies)))
  216. (n-freq (mapcar (lambda (freq) `(,(car freq) . ,(/ (float (cdr freq)) total-count))) frequencies))
  217. (f-pick (list (car (car n-freq))))
  218. (1-2-ratio (/ (cdr (nth 0 n-freq))
  219. (cdr (nth 1 n-freq))))
  220. (2-3-ratio (/ (cdr (nth 1 n-freq))
  221. (cdr (nth 2 n-freq))))
  222. (1-3-ratio (* 1-2-ratio 2-3-ratio))
  223. (1-val (car (nth 0 n-freq)))
  224. (2-val (car (nth 1 n-freq)))
  225. (3-val (car (nth 2 n-freq))))
  226. (when (> 1-2-ratio 4) (push 1-val f-pick))
  227. (when (and (< 1-2-ratio 2-val)
  228. (< (* (apply #'* f-pick) 2-val) 30))
  229. (push 2-val f-pick))
  230. (when (and (< 1-3-ratio 3-val)
  231. (< (* (apply #'* f-pick) 3-val) 30))
  232. (push 3-val f-pick))
  233. f-pick))))
  234. (defun org--plot/merge-alists (function default alist1 alist2 &rest alists)
  235. "Using FUNCTION, combine the elements of all given ALISTS. When an element is
  236. only present in one alist, DEFAULT is used as the second argument for the FUNCTION."
  237. (when (> (length alists) 0)
  238. (setq alist2 (apply #'org--plot/merge-alists function default alist2 alists)))
  239. (flet ((keys (alist) (mapcar #'car alist))
  240. (lookup (key alist) (or (cdr (assoc key alist)) default)))
  241. (loop with keys = (union (keys alist1) (keys alist2) :test 'equal)
  242. for k in keys collect
  243. (cons k (funcall function (lookup k alist1) (lookup k alist2))))))
  244. (defun org--plot/item-frequencies (values &optional normalise)
  245. "Return an alist indicating the frequency of values in VALUES list."
  246. (let ((normaliser (if normalise (float (length values)) 1)))
  247. (cl-loop for (n . m) in (seq-group-by #'identity values)
  248. collect (cons n (/ (length m) normaliser)))))
  249. (defun org--plot/prime-factors (value)
  250. "Return the prime decomposition of VALUE, e.g. for 12, '(3 2 2)"
  251. (let ((factors '(1)) (i 1))
  252. (while (/= 1 value)
  253. (setq i (1+ i))
  254. (when (eq 0 (% value i))
  255. (push i factors)
  256. (setq value (/ value i))
  257. (setq i (1- i))
  258. ))
  259. (subseq factors 0 -1)))
  260. (defcustom org-plot/gnuplot-script-preamble ""
  261. "String or function which provides content to be inserted into the GNUPlot
  262. script before the plot command. Not that this is in addition to, not instead of
  263. other content generated in `org-plot/gnuplot-script'.
  264. If a function, it is called with the plot type as the argument."
  265. :group 'org-plot
  266. :type '(choice string function))
  267. (defcustom org-plot/preset-plot-types
  268. '((2d (lambda (data-file num-cols params plot-str)
  269. (let* ((type (plist-get params :plot-type))
  270. (with (if (eq type 'grid) 'pm3d (plist-get params :with)))
  271. (ind (plist-get params :ind))
  272. (deps (if (plist-member params :deps) (plist-get params :deps)))
  273. (text-ind (plist-get params :textind))
  274. (col-labels (plist-get params :labels))
  275. res)
  276. (dotimes (col num-cols res)
  277. (unless (and (eq type '2d)
  278. (or (and ind (equal (1+ col) ind))
  279. (and deps (not (member (1+ col) deps)))))
  280. (setf res
  281. (cons
  282. (format plot-str data-file
  283. (or (and ind (> ind 0)
  284. (not text-ind)
  285. (format "%d:" ind)) "")
  286. (1+ col)
  287. (if text-ind (format ":xticlabel(%d)" ind) "")
  288. with
  289. (or (nth col col-labels)
  290. (format "%d" (1+ col))))
  291. res)))))))
  292. (3d (lambda (data-file num-cols params plot-str)
  293. (let* ((type (plist-get params :plot-type))
  294. (with (if (eq type 'grid) 'pm3d (plist-get params :with))))
  295. (list (format "'%s' matrix with %s title ''"
  296. data-file with)))))
  297. (grid (lambda (data-file num-cols params plot-str)
  298. (let* ((type (plist-get params :plot-type))
  299. (with (if (eq type 'grid) 'pm3d (plist-get params :with))))
  300. (list (format "'%s' with %s title ''"
  301. data-file with)))))
  302. (radar (lambda (data-file num-cols params plot-str)
  303. (list (org--plot/radar table params)))))
  304. "List of plot presets with the type name as the car, and a function
  305. which yeilds plot-lines (a list of strings) as the cdr.
  306. The parameters of `org-plot/gnuplot-script' and PLOT-STR are passed to
  307. that function. i.e. it is called with the following arguments:
  308. DATA-FILE NUM-COLS PARAMS PLOT-STR"
  309. :group 'org-plot
  310. :type '(alist :value-type (symbol group)))
  311. (defvar org--plot/radar-template
  312. "### spider plot/chart with gnuplot
  313. # also known as: radar chart, web chart, star chart, cobweb chart,
  314. # radar plot, web plot, star plot, cobweb plot, etc. ...
  315. set datafile separator ' '
  316. set size square
  317. unset tics
  318. set angles degree
  319. set key bmargin center horizontal
  320. unset border
  321. # Load data and settup
  322. load \"%s\"
  323. # General settings
  324. DataColCount = words($Data[1])-1
  325. AxesCount = |$Data|-HeaderLines
  326. AngleOffset = 90
  327. Max = 1
  328. d=0.1*Max
  329. Direction = -1 # counterclockwise=1, clockwise = -1
  330. # Tic settings
  331. TicCount = %s
  332. TicOffset = 0.1
  333. TicValue(axis,i) = real(i)*(word($Settings[axis],3)-word($Settings[axis],2)) \\
  334. / word($Settings[axis],4)+word($Settings[axis],2)
  335. TicLabelPosX(axis,i) = PosX(axis,i/TicCount) + PosY(axis, TicOffset)
  336. TicLabelPosY(axis,i) = PosY(axis,i/TicCount) - PosX(axis, TicOffset)
  337. TicLen = 0.03
  338. TicdX(axis,i) = 0.5*TicLen*cos(alpha(axis)-90)
  339. TicdY(axis,i) = 0.5*TicLen*sin(alpha(axis)-90)
  340. # Label
  341. LabOffset = 0.10
  342. LabX(axis) = PosX(axis+1,Max+2*d) + PosY(axis, LabOffset)
  343. LabY(axis) = PosY($0+1,Max+2*d)
  344. # Functions
  345. alpha(axis) = (axis-1)*Direction*360.0/AxesCount+AngleOffset
  346. PosX(axis,R) = R*cos(alpha(axis))
  347. PosY(axis,R) = R*sin(alpha(axis))
  348. Scale(axis,value) = real(value-word($Settings[axis],2))/(word($Settings[axis],3)-word($Settings[axis],2))
  349. # Spider settings
  350. set style arrow 1 dt 1 lw 1.0 @fgal head filled size 0.06,25 # style for axes
  351. set style arrow 2 dt 2 lw 0.5 @fgal nohead # style for weblines
  352. set style arrow 3 dt 1 lw 1 @fgal nohead # style for axis tics
  353. set samples AxesCount
  354. set isosamples TicCount
  355. set urange[1:AxesCount]
  356. set vrange[1:TicCount]
  357. set style fill transparent solid 0.2
  358. set xrange[-Max-4*d:Max+4*d]
  359. set yrange[-Max-4*d:Max+4*d]
  360. plot \\
  361. '+' u (0):(0):(PosX($0,Max+d)):(PosY($0,Max+d)) w vec as 1 not, \\
  362. $Data u (LabX($0)): \\
  363. (LabY($0)):1 every ::HeaderLines w labels center enhanced @fgt not, \\
  364. for [i=1:DataColCount] $Data u (PosX($0+1,Scale($0+1,column(i+1)))): \\
  365. (PosY($0+1,Scale($0+1,column(i+1)))) every ::HeaderLines w filledcurves lt i title word($Data[1],i+1), \\
  366. %s
  367. # '++' u (PosX($1,$2/TicCount)-TicdX($1,$2/TicCount)): \\
  368. # (PosY($1,$2/TicCount)-TicdY($1,$2/TicCount)): \\
  369. # (2*TicdX($1,$2/TicCount)):(2*TicdY($1,$2/TicCount)) \\
  370. # w vec as 3 not, \\
  371. ### end of code
  372. ")
  373. (defvar org--plot/radar-ticks
  374. " '++' u (PosX($1,$2/TicCount)):(PosY($1,$2/TicCount)): \\
  375. (PosX($1+1,$2/TicCount)-PosX($1,$2/TicCount)): \\
  376. (PosY($1+1,$2/TicCount)-PosY($1,$2/TicCount)) w vec as 2 not, \\
  377. '++' u (TicLabelPosX(%s,$2)):(TicLabelPosY(%s,$2)): \\
  378. (sprintf('%%g',TicValue(%s,$2))) w labels font ',8' @fgat not")
  379. (defvar org--plot/radar-setup-template
  380. "# Data
  381. $Data <<HEREHAVESOMEDATA
  382. %s
  383. HEREHAVESOMEDATA
  384. HeaderLines = 1
  385. # Settings for scale and offset adjustments
  386. # axis min max tics axisLabelXoff axisLabelYoff
  387. $Settings <<EOD
  388. %s
  389. EOD
  390. ")
  391. (defun org--plot/radar (table params)
  392. (let* ((data
  393. (concat "\"" (s-join "\" \"" (plist-get params :labels)) "\""
  394. "\n"
  395. (s-join "\n"
  396. (mapcar (lambda (row)
  397. (format
  398. "\"%s\" %s"
  399. (car row)
  400. (s-join " " (cdr row))))
  401. table))))
  402. (ticks (or (plist-get params :ticks)
  403. (org--plot/sensible-tick-num table
  404. (plist-get params :ymin)
  405. (plist-get params :ymax))))
  406. (settings
  407. (s-join "\n"
  408. (mapcar (lambda (row)
  409. (let ((data (org--plot/values-stats
  410. (mapcar #'string-to-number (cdr row)))))
  411. (format
  412. "\"%s\" %s %s %s"
  413. (car row)
  414. (or (plist-get params :ymin)
  415. (plist-get data :nice-min))
  416. (or (plist-get params :ymax)
  417. (plist-get data :nice-max))
  418. (if (eq ticks 0) 2 ticks)
  419. )))
  420. table)))
  421. (setup-file (make-temp-file "org-plot-setup")))
  422. (f-write-text (format org--plot/radar-setup-template data settings)
  423. 'utf-8 setup-file)
  424. (format org--plot/radar-template
  425. setup-file
  426. (if (eq ticks 0) 2 ticks)
  427. (if (eq ticks 0) ""
  428. (apply #'format org--plot/radar-ticks
  429. (make-list 3 (if (and (plist-get params :ymin)
  430. (plist-get params :ymax))
  431. ;; FIXME multi-drawing of tick labels with "1"
  432. "1" "$1")))))))
  433. (defcustom org-plot/gnuplot-term-extra ""
  434. "String or function which provides the extra term options.
  435. E.g. a value of \"size 1050,650\" would cause
  436. \"set term ... size 1050,650\" to be used.
  437. If a function, it is called with the plot type as the argument."
  438. :group 'org-plot
  439. :type '(choice string function))
  440. (defun org-plot/gnuplot-script (data-file num-cols params &optional preface)
  441. "Write a gnuplot script to DATA-FILE respecting the options set in PARAMS.
  442. NUM-COLS controls the number of columns plotted in a 2-d plot.
  443. Optional argument PREFACE returns only option parameters in a
  444. manner suitable for prepending to a user-specified script."
  445. (let* ((type (plist-get params :plot-type))
  446. (with (if (eq type 'grid) 'pm3d (plist-get params :with)))
  447. (sets (plist-get params :set))
  448. (lines (plist-get params :line))
  449. (map (plist-get params :map))
  450. (title (plist-get params :title))
  451. (file (plist-get params :file))
  452. (ind (plist-get params :ind))
  453. (time-ind (plist-get params :timeind))
  454. (timefmt (plist-get params :timefmt))
  455. (text-ind (plist-get params :textind))
  456. (deps (if (plist-member params :deps) (plist-get params :deps)))
  457. (col-labels (plist-get params :labels))
  458. (x-labels (plist-get params :xlabels))
  459. (y-labels (plist-get params :ylabels))
  460. (plot-str "'%s' using %s%d%s with %s title '%s'")
  461. (plot-cmd (pcase type
  462. (`2d "plot")
  463. (`3d "splot")
  464. (`grid "splot")))
  465. (script "reset")
  466. ;; ats = add-to-script
  467. (ats (lambda (line) (setf script (concat script "\n" line))))
  468. plot-lines)
  469. ;; handle output file, background, and size
  470. (funcall ats (format "set term %s %s"
  471. (if file (file-name-extension file) "GNUTERM")
  472. (if (stringp org-plot/gnuplot-term-extra)
  473. org-plot/gnuplot-term-extra
  474. (org-plot/gnuplot-term-extra type))))
  475. (when file ; output file
  476. (funcall ats (format "set output '%s'" file)))
  477. (funcall ats
  478. (if (stringp org-plot/gnuplot-script-preamble)
  479. org-plot/gnuplot-script-preamble
  480. (org-plot/gnuplot-script-preamble type)))
  481. (pcase type ; type
  482. (`2d ())
  483. (`3d (when map (funcall ats "set map")))
  484. (`grid (funcall ats (if map "set pm3d map" "set pm3d"))))
  485. (when title (funcall ats (format "set title '%s'" title))) ; title
  486. (mapc ats lines) ; line
  487. (dolist (el sets) (funcall ats (format "set %s" el))) ; set
  488. ;; Unless specified otherwise, values are TAB separated.
  489. (unless (string-match-p "^set datafile separator" script)
  490. (funcall ats "set datafile separator \"\\t\""))
  491. (when x-labels ; x labels (xtics)
  492. (funcall ats
  493. (format "set xtics (%s)"
  494. (mapconcat (lambda (pair)
  495. (format "\"%s\" %d" (cdr pair) (car pair)))
  496. x-labels ", "))))
  497. (when y-labels ; y labels (ytics)
  498. (funcall ats
  499. (format "set ytics (%s)"
  500. (mapconcat (lambda (pair)
  501. (format "\"%s\" %d" (cdr pair) (car pair)))
  502. y-labels ", "))))
  503. (when time-ind ; timestamp index
  504. (funcall ats "set xdata time")
  505. (funcall ats (concat "set timefmt \""
  506. (or timefmt ; timefmt passed to gnuplot
  507. "%Y-%m-%d-%H:%M:%S") "\"")))
  508. (unless preface
  509. (let ((type-func (cadr (assoc type org-plot/preset-plot-types))))
  510. (when type-func
  511. (setq plot-lines
  512. (funcall type-func data-file num-cols params plot-str))))
  513. (funcall ats
  514. (concat plot-cmd " " (mapconcat #'identity
  515. (reverse plot-lines)
  516. ",\\\n "))))
  517. script))
  518. ;;-----------------------------------------------------------------------------
  519. ;; facade functions
  520. ;;;###autoload
  521. (defun org-plot/gnuplot (&optional params)
  522. "Plot table using gnuplot. Gnuplot options can be specified with PARAMS.
  523. If not given options will be taken from the +PLOT
  524. line directly before or after the table."
  525. (interactive)
  526. (require 'gnuplot)
  527. (save-window-excursion
  528. (delete-other-windows)
  529. (when (get-buffer "*gnuplot*") ; reset *gnuplot* if it already running
  530. (with-current-buffer "*gnuplot*"
  531. (goto-char (point-max))))
  532. (org-plot/goto-nearest-table)
  533. ;; Set default options.
  534. (dolist (pair org-plot/gnuplot-default-options)
  535. (unless (plist-member params (car pair))
  536. (setf params (plist-put params (car pair) (cdr pair)))))
  537. ;; Collect options.
  538. (save-excursion (while (and (equal 0 (forward-line -1))
  539. (looking-at "[[:space:]]*#\\+"))
  540. (setf params (org-plot/collect-options params))))
  541. ;; collect table and table information
  542. (let* ((data-file (make-temp-file "org-plot"))
  543. (table (let ((tbl (org-table-to-lisp)))
  544. (when (pcase (plist-get params :transpose)
  545. ('y t)
  546. ('yes t)
  547. ('t t))
  548. (if (not (memq 'hline tbl))
  549. (setq tbl (apply #'cl-mapcar #'list tbl))
  550. ;; When present, remove hlines as they can't (currentily) be easily transposed.
  551. (setq tbl (apply #'cl-mapcar #'list
  552. (remove 'hline tbl)))
  553. (push 'hline (cdr tbl))))
  554. tbl))
  555. (num-cols (length (if (eq (nth 0 table) 'hline) (nth 1 table)
  556. (nth 0 table)))))
  557. (run-with-idle-timer 0.1 nil #'delete-file data-file)
  558. (when (eq (cadr table) 'hline)
  559. (setf params
  560. (plist-put params :labels (car table))) ; headers to labels
  561. (setf table (delq 'hline (cdr table)))) ; clean non-data from table
  562. ;; Collect options.
  563. (save-excursion (while (and (equal 0 (forward-line -1))
  564. (looking-at "[[:space:]]*#\\+"))
  565. (setf params (org-plot/collect-options params))))
  566. ;; Dump table to datafile (very different for grid).
  567. (pcase (plist-get params :plot-type)
  568. (`2d (org-plot/gnuplot-to-data table data-file params))
  569. (`3d (org-plot/gnuplot-to-data table data-file params))
  570. (`grid (let ((y-labels (org-plot/gnuplot-to-grid-data
  571. table data-file params)))
  572. (when y-labels (plist-put params :ylabels y-labels)))))
  573. ;; Check type of ind column (timestamp? text?)
  574. (when (eq `2d (plist-get params :plot-type))
  575. (let* ((ind (1- (plist-get params :ind)))
  576. (ind-column (mapcar (lambda (row) (nth ind row)) table)))
  577. (cond ((< ind 0) nil) ; ind is implicit
  578. ((cl-every (lambda (el)
  579. (string-match org-ts-regexp3 el))
  580. ind-column)
  581. (plist-put params :timeind t)) ; ind holds timestamps
  582. ((or (string= (plist-get params :with) "hist")
  583. (cl-notevery (lambda (el)
  584. (string-match org-table-number-regexp el))
  585. ind-column))
  586. (plist-put params :textind t))))) ; ind holds text
  587. ;; Write script.
  588. (with-temp-buffer
  589. (if (plist-get params :script) ; user script
  590. (progn (insert
  591. (org-plot/gnuplot-script data-file num-cols params t))
  592. (insert "\n")
  593. (insert-file-contents (plist-get params :script))
  594. (goto-char (point-min))
  595. (while (re-search-forward "\\$datafile" nil t)
  596. (replace-match data-file nil nil)))
  597. (insert (org-plot/gnuplot-script data-file num-cols params)))
  598. ;; Graph table.
  599. (gnuplot-mode)
  600. (gnuplot-send-buffer-to-gnuplot))
  601. ;; Cleanup.
  602. (bury-buffer (get-buffer "*gnuplot*")))))
  603. (provide 'org-plot)
  604. ;; Local variables:
  605. ;; generated-autoload-file: "org-loaddefs.el"
  606. ;; End:
  607. ;;; org-plot.el ends here