org-plot.el 27 KB

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