org-plot.el 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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 (if (= range 0) 0
  178. (ceiling (- 1 (log10 range)))))
  179. (range-factor (expt 10 rangeOrder))
  180. (nice-min (if (= range 0) (car nums)
  181. (/ (float (floor (* minimum range-factor))) range-factor)))
  182. (nice-max (if (= range 0) (car nums)
  183. (/ (float (ceiling (* maximum range-factor))) range-factor))))
  184. `(:min ,minimum :max ,maximum :range ,range
  185. :range-factor ,range-factor
  186. :nice-min ,nice-min :nice-max ,nice-max :nice-range ,(- nice-max nice-min))))
  187. (defun org--plot/sensible-tick-num (table &optional hard-min hard-max)
  188. "From a the values in a TABLE of data, attempt to guess an appropriate number of ticks."
  189. (let* ((row-data
  190. (mapcar (lambda (row) (org--plot/values-stats
  191. (mapcar #'string-to-number (cdr row))
  192. hard-min
  193. hard-max)) table))
  194. (row-normalised-ranges (mapcar (lambda (r-data)
  195. (let ((val (round (*
  196. (plist-get r-data :range-factor)
  197. (plist-get r-data :nice-range)))))
  198. (if (= (% val 10) 0) (/ val 10) val)))
  199. row-data))
  200. (range-prime-decomposition (mapcar #'org--plot/prime-factors row-normalised-ranges))
  201. (weighted-factors (sort (apply #'org--plot/merge-alists #'+ 0
  202. (mapcar (lambda (factors) (org--plot/item-frequencies factors t))
  203. range-prime-decomposition))
  204. (lambda (a b) (> (cdr a) (cdr b))))))
  205. (apply #'* (org--plot/nice-frequency-pick weighted-factors))))
  206. (defun org--plot/nice-frequency-pick (frequencies)
  207. "From a list of frequences, try to sensibly pick a sample of the most frequent."
  208. ;; TODO this mosly works decently, but counld do with some tweaking to work more consistently.
  209. (case (length frequencies)
  210. (1 (list (car (nth 0 frequencies))))
  211. (2 (if (<= 3 (/ (cdr (nth 0 frequencies))
  212. (cdr (nth 1 frequencies))))
  213. (make-list 2
  214. (car (nth 0 frequencies)))
  215. (list (car (nth 0 frequencies))
  216. (car (nth 1 frequencies)))))
  217. (t
  218. (let* ((total-count (apply #'+ (mapcar #'cdr frequencies)))
  219. (n-freq (mapcar (lambda (freq) `(,(car freq) . ,(/ (float (cdr freq)) total-count))) frequencies))
  220. (f-pick (list (car (car n-freq))))
  221. (1-2-ratio (/ (cdr (nth 0 n-freq))
  222. (cdr (nth 1 n-freq))))
  223. (2-3-ratio (/ (cdr (nth 1 n-freq))
  224. (cdr (nth 2 n-freq))))
  225. (1-3-ratio (* 1-2-ratio 2-3-ratio))
  226. (1-val (car (nth 0 n-freq)))
  227. (2-val (car (nth 1 n-freq)))
  228. (3-val (car (nth 2 n-freq))))
  229. (when (> 1-2-ratio 4) (push 1-val f-pick))
  230. (when (and (< 1-2-ratio 2-val)
  231. (< (* (apply #'* f-pick) 2-val) 30))
  232. (push 2-val f-pick))
  233. (when (and (< 1-3-ratio 3-val)
  234. (< (* (apply #'* f-pick) 3-val) 30))
  235. (push 3-val f-pick))
  236. f-pick))))
  237. (defun org--plot/merge-alists (function default alist1 alist2 &rest alists)
  238. "Using FUNCTION, combine the elements of all given ALISTS. When an element is
  239. only present in one alist, DEFAULT is used as the second argument for the FUNCTION."
  240. (when (> (length alists) 0)
  241. (setq alist2 (apply #'org--plot/merge-alists function default alist2 alists)))
  242. (cl-flet ((keys (alist) (mapcar #'car alist))
  243. (lookup (key alist) (or (cdr (assoc key alist)) default)))
  244. (cl-loop with keys = (cl-union (keys alist1) (keys alist2) :test 'equal)
  245. for k in keys collect
  246. (cons k (funcall function (lookup k alist1) (lookup k alist2))))))
  247. (defun org--plot/item-frequencies (values &optional normalise)
  248. "Return an alist indicating the frequency of values in VALUES list."
  249. (let ((normaliser (if normalise (float (length values)) 1)))
  250. (cl-loop for (n . m) in (seq-group-by #'identity values)
  251. collect (cons n (/ (length m) normaliser)))))
  252. (defun org--plot/prime-factors (value)
  253. "Return the prime decomposition of VALUE, e.g. for 12, '(3 2 2)"
  254. (let ((factors '(1)) (i 1))
  255. (while (/= 1 value)
  256. (setq i (1+ i))
  257. (when (eq 0 (% value i))
  258. (push i factors)
  259. (setq value (/ value i))
  260. (setq i (1- i))
  261. ))
  262. (cl-subseq factors 0 -1)))
  263. (defcustom org-plot/gnuplot-script-preamble ""
  264. "String or function which provides content to be inserted into the GNUPlot
  265. script before the plot command. Not that this is in addition to, not instead of
  266. other content generated in `org-plot/gnuplot-script'.
  267. If a function, it is called with the plot type as the argument."
  268. :group 'org-plot
  269. :type '(choice string function))
  270. (defcustom org-plot/preset-plot-types
  271. '((2d :plot-cmd "plot"
  272. :check-ind-type t
  273. :plot-func
  274. (lambda (_table data-file num-cols params plot-str)
  275. (let* ((type (plist-get params :plot-type))
  276. (with (if (eq type 'grid) 'pm3d (plist-get params :with)))
  277. (ind (plist-get params :ind))
  278. (deps (if (plist-member params :deps) (plist-get params :deps)))
  279. (text-ind (plist-get params :textind))
  280. (col-labels (plist-get params :labels))
  281. res)
  282. (dotimes (col num-cols res)
  283. (unless (and (eq type '2d)
  284. (or (and ind (equal (1+ col) ind))
  285. (and deps (not (member (1+ col) deps)))))
  286. (setf res
  287. (cons
  288. (format plot-str data-file
  289. (or (and ind (> ind 0)
  290. (not text-ind)
  291. (format "%d:" ind)) "")
  292. (1+ col)
  293. (if text-ind (format ":xticlabel(%d)" ind) "")
  294. with
  295. (or (nth col col-labels)
  296. (format "%d" (1+ col))))
  297. res)))))))
  298. (3d :plot-cmd "splot"
  299. :plot-pre (lambda (_table _data-file _num-cols params _plot-str)
  300. (if (plist-get params :map) "set map"))
  301. :plot-func
  302. (lambda (_table data-file _num-cols params _plot-str)
  303. (let* ((type (plist-get params :plot-type))
  304. (with (if (eq type 'grid) 'pm3d (plist-get params :with))))
  305. (list (format "'%s' matrix with %s title ''"
  306. data-file with)))))
  307. (grid :plot-cmd "splot"
  308. :plot-pre (lambda (_table _data-file _num-cols params _plot-str)
  309. (if (plist-get params :map) "set pm3d map" "set map"))
  310. :data-dump (lambda (table data-file params _num-cols)
  311. (let ((y-labels (org-plot/gnuplot-to-grid-data
  312. table data-file params)))
  313. (when y-labels (plist-put params :ylabels y-labels))))
  314. :plot-func
  315. (lambda (table data-file _num-cols params _plot-str)
  316. (let* ((type (plist-get params :plot-type))
  317. (with (if (eq type 'grid) 'pm3d (plist-get params :with))))
  318. (list (format "'%s' with %s title ''"
  319. data-file with)))))
  320. (radar :plot-func
  321. (lambda (table _data-file _num-cols params plot-str)
  322. (list (org--plot/radar table params)))))
  323. "List of plists describing the avalible plot types.
  324. The car is the type name, and the property :plot-func must be set.
  325. The value of :plot-func is a lambda which yields plot-lines
  326. (a list of strings) as the cdr.
  327. All lambda functions have the parameters of `org-plot/gnuplot-script' and PLOT-STR passed to them.
  328. i.e. they are called with the following signature: (TABLE DATA-FILE NUM-COLS PARAMS PLOT-STR)
  329. Potentially useful parameters in PARAMS include:
  330. :set :line :map :title :file :ind :timeind :timefmt :textind
  331. :deps :labels :xlabels :ylabels :xmin :xmax :ymin :ymax :ticks
  332. In addition to :plot-func, the following optional properties may be set.
  333. - :plot-cmd - A gnuplot command appended to each plot-line.
  334. Accepts string or nil. Default value: nil.
  335. - :check-ind-type - Whether the types of ind values should be checked.
  336. Accepts boolean.
  337. - :plot-str - the formula string passed to :plot-func as PLOT-STR
  338. Accepts string. Default value: \"'%s' using %s%d%s with %s title '%s'\"
  339. - :data-dump - Function to dump the table to a datafile for ease of use.
  340. Accepts lambda function. Default lambda body: (org-plot/gnuplot-to-data table data-file params)
  341. - :plot-pre - Gnuplot code to be inserted early into the script, just after term and output have been set.
  342. Accepts string, nil, or lambda function which returns string or nil. Defaults to nil.
  343. "
  344. :group 'org-plot
  345. :type '(alist :value-type (symbol group)))
  346. (defvar org--plot/radar-template
  347. "### spider plot/chart with gnuplot
  348. # also known as: radar chart, web chart, star chart, cobweb chart,
  349. # radar plot, web plot, star plot, cobweb plot, etc. ...
  350. set datafile separator ' '
  351. set size square
  352. unset tics
  353. set angles degree
  354. set key bmargin center horizontal
  355. unset border
  356. # Load data and settup
  357. load \"%s\"
  358. # General settings
  359. DataColCount = words($Data[1])-1
  360. AxesCount = |$Data|-HeaderLines-1
  361. AngleOffset = 90
  362. Max = 1
  363. d=0.1*Max
  364. Direction = -1 # counterclockwise=1, clockwise = -1
  365. # Tic settings
  366. TicCount = %s
  367. TicOffset = 0.1
  368. TicValue(axis,i) = real(i)*(word($Settings[axis],3)-word($Settings[axis],2)) \\
  369. / word($Settings[axis],4)+word($Settings[axis],2)
  370. TicLabelPosX(axis,i) = PosX(axis,i/TicCount) + PosY(axis, TicOffset)
  371. TicLabelPosY(axis,i) = PosY(axis,i/TicCount) - PosX(axis, TicOffset)
  372. TicLen = 0.03
  373. TicdX(axis,i) = 0.5*TicLen*cos(alpha(axis)-90)
  374. TicdY(axis,i) = 0.5*TicLen*sin(alpha(axis)-90)
  375. # Label
  376. LabOffset = 0.10
  377. LabX(axis) = PosX(axis+1,Max+2*d) + PosY(axis, LabOffset)
  378. LabY(axis) = PosY($0+1,Max+2*d)
  379. # Functions
  380. alpha(axis) = (axis-1)*Direction*360.0/AxesCount+AngleOffset
  381. PosX(axis,R) = R*cos(alpha(axis))
  382. PosY(axis,R) = R*sin(alpha(axis))
  383. Scale(axis,value) = real(value-word($Settings[axis],2))/(word($Settings[axis],3)-word($Settings[axis],2))
  384. # Spider settings
  385. set style arrow 1 dt 1 lw 1.0 @fgal head filled size 0.06,25 # style for axes
  386. set style arrow 2 dt 2 lw 0.5 @fgal nohead # style for weblines
  387. set style arrow 3 dt 1 lw 1 @fgal nohead # style for axis tics
  388. set samples AxesCount
  389. set isosamples TicCount
  390. set urange[1:AxesCount]
  391. set vrange[1:TicCount]
  392. set style fill transparent solid 0.2
  393. set xrange[-Max-4*d:Max+4*d]
  394. set yrange[-Max-4*d:Max+4*d]
  395. plot \\
  396. '+' u (0):(0):(PosX($0,Max+d)):(PosY($0,Max+d)) w vec as 1 not, \\
  397. $Data u (LabX($0)): \\
  398. (LabY($0)):1 every ::HeaderLines w labels center enhanced @fgt not, \\
  399. for [i=1:DataColCount] $Data u (PosX($0+1,Scale($0+1,column(i+1)))): \\
  400. (PosY($0+1,Scale($0+1,column(i+1)))) every ::HeaderLines w filledcurves lt i title word($Data[1],i+1), \\
  401. %s
  402. # '++' u (PosX($1,$2/TicCount)-TicdX($1,$2/TicCount)): \\
  403. # (PosY($1,$2/TicCount)-TicdY($1,$2/TicCount)): \\
  404. # (2*TicdX($1,$2/TicCount)):(2*TicdY($1,$2/TicCount)) \\
  405. # w vec as 3 not, \\
  406. ### end of code
  407. ")
  408. (defvar org--plot/radar-ticks
  409. " '++' u (PosX($1,$2/TicCount)):(PosY($1,$2/TicCount)): \\
  410. (PosX($1+1,$2/TicCount)-PosX($1,$2/TicCount)): \\
  411. (PosY($1+1,$2/TicCount)-PosY($1,$2/TicCount)) w vec as 2 not, \\
  412. '++' u (TicLabelPosX(%s,$2)):(TicLabelPosY(%s,$2)): \\
  413. (sprintf('%%g',TicValue(%s,$2))) w labels font ',8' @fgat not")
  414. (defvar org--plot/radar-setup-template
  415. "# Data
  416. $Data <<HEREHAVESOMEDATA
  417. %s
  418. HEREHAVESOMEDATA
  419. HeaderLines = 1
  420. # Settings for scale and offset adjustments
  421. # axis min max tics axisLabelXoff axisLabelYoff
  422. $Settings <<EOD
  423. %s
  424. EOD
  425. ")
  426. (defun org--plot/radar (table params)
  427. (let* ((data
  428. (concat "\"" (s-join "\" \"" (plist-get params :labels)) "\""
  429. "\n"
  430. (s-join "\n"
  431. (mapcar (lambda (row)
  432. (format
  433. "\"%s\" %s"
  434. (car row)
  435. (s-join " " (cdr row))))
  436. (append table (list (car table)))))))
  437. (ticks (or (plist-get params :ticks)
  438. (org--plot/sensible-tick-num table
  439. (plist-get params :ymin)
  440. (plist-get params :ymax))))
  441. (settings
  442. (s-join "\n"
  443. (mapcar (lambda (row)
  444. (let ((data (org--plot/values-stats
  445. (mapcar #'string-to-number (cdr row)))))
  446. (format
  447. "\"%s\" %s %s %s"
  448. (car row)
  449. (or (plist-get params :ymin)
  450. (plist-get data :nice-min))
  451. (or (plist-get params :ymax)
  452. (plist-get data :nice-max))
  453. (if (eq ticks 0) 2 ticks)
  454. )))
  455. (append table (list (car table))))))
  456. (setup-file (make-temp-file "org-plot-setup")))
  457. (let ((coding-system-for-write 'utf-8))
  458. (write-region (format org--plot/radar-setup-template data settings) nil setup-file nil :silent))
  459. (format org--plot/radar-template
  460. setup-file
  461. (if (eq ticks 0) 2 ticks)
  462. (if (eq ticks 0) ""
  463. (apply #'format org--plot/radar-ticks
  464. (make-list 3 (if (and (plist-get params :ymin)
  465. (plist-get params :ymax))
  466. ;; FIXME multi-drawing of tick labels with "1"
  467. "1" "$1")))))))
  468. (defcustom org-plot/gnuplot-term-extra ""
  469. "String or function which provides the extra term options.
  470. E.g. a value of \"size 1050,650\" would cause
  471. \"set term ... size 1050,650\" to be used.
  472. If a function, it is called with the plot type as the argument."
  473. :group 'org-plot
  474. :type '(choice string function))
  475. (defun org-plot/gnuplot-script (table data-file num-cols params &optional preface)
  476. "Write a gnuplot script to DATA-FILE respecting the options set in PARAMS.
  477. NUM-COLS controls the number of columns plotted in a 2-d plot.
  478. Optional argument PREFACE returns only option parameters in a
  479. manner suitable for prepending to a user-specified script."
  480. (let* ((type-name (plist-get params :plot-type))
  481. (type (cdr (assoc type-name org-plot/preset-plot-types))))
  482. (unless type
  483. (user-error "Org-plot type `%s' is undefined." type-name))
  484. (let* ((sets (plist-get params :set))
  485. (lines (plist-get params :line))
  486. (map (plist-get params :map))
  487. (title (plist-get params :title))
  488. (file (plist-get params :file))
  489. (ind (plist-get params :ind))
  490. (time-ind (plist-get params :timeind))
  491. (timefmt (plist-get params :timefmt))
  492. (text-ind (plist-get params :textind))
  493. (deps (if (plist-member params :deps) (plist-get params :deps)))
  494. (col-labels (plist-get params :labels))
  495. (x-labels (plist-get params :xlabels))
  496. (y-labels (plist-get params :ylabels))
  497. (plot-str (or (plist-get type :plot-str)
  498. "'%s' using %s%d%s with %s title '%s'"))
  499. (plot-cmd (plist-get type :plot-cmd))
  500. (plot-pre (plist-get type :plot-pre))
  501. (script "reset")
  502. ;; ats = add-to-script
  503. (ats (lambda (line) (when line (setf script (concat script "\n" line)))))
  504. plot-lines)
  505. ;; handle output file, background, and size
  506. (funcall ats (format "set term %s %s"
  507. (if file (file-name-extension file) "GNUTERM")
  508. (if (stringp org-plot/gnuplot-term-extra)
  509. org-plot/gnuplot-term-extra
  510. (funcall org-plot/gnuplot-term-extra type))))
  511. (when file ; output file
  512. (funcall ats (format "set output '%s'" file)))
  513. (when plot-pre
  514. (funcall ats (funcall plot-pre table data-file num-cols params plot-str)))
  515. (funcall ats
  516. (if (stringp org-plot/gnuplot-script-preamble)
  517. org-plot/gnuplot-script-preamble
  518. (funcall org-plot/gnuplot-script-preamble type)))
  519. (when title (funcall ats (format "set title '%s'" title))) ; title
  520. (mapc ats lines) ; line
  521. (dolist (el sets) (funcall ats (format "set %s" el))) ; set
  522. ;; Unless specified otherwise, values are TAB separated.
  523. (unless (string-match-p "^set datafile separator" script)
  524. (funcall ats "set datafile separator \"\\t\""))
  525. (when x-labels ; x labels (xtics)
  526. (funcall ats
  527. (format "set xtics (%s)"
  528. (mapconcat (lambda (pair)
  529. (format "\"%s\" %d" (cdr pair) (car pair)))
  530. x-labels ", "))))
  531. (when y-labels ; y labels (ytics)
  532. (funcall ats
  533. (format "set ytics (%s)"
  534. (mapconcat (lambda (pair)
  535. (format "\"%s\" %d" (cdr pair) (car pair)))
  536. y-labels ", "))))
  537. (when time-ind ; timestamp index
  538. (funcall ats "set xdata time")
  539. (funcall ats (concat "set timefmt \""
  540. (or timefmt ; timefmt passed to gnuplot
  541. "%Y-%m-%d-%H:%M:%S") "\"")))
  542. (unless preface
  543. (let ((type-func (plist-get type :plot-func)))
  544. (when type-func
  545. (setq plot-lines
  546. (funcall type-func table data-file num-cols params plot-str))))
  547. (funcall ats
  548. (concat plot-cmd
  549. (when plot-cmd " ")
  550. (mapconcat #'identity
  551. (reverse plot-lines)
  552. ",\\\n "))))
  553. script)))
  554. ;;-----------------------------------------------------------------------------
  555. ;; facade functions
  556. ;;;###autoload
  557. (defun org-plot/gnuplot (&optional params)
  558. "Plot table using gnuplot. Gnuplot options can be specified with PARAMS.
  559. If not given options will be taken from the +PLOT
  560. line directly before or after the table."
  561. (interactive)
  562. (require 'gnuplot)
  563. (save-window-excursion
  564. (delete-other-windows)
  565. (when (get-buffer "*gnuplot*") ; reset *gnuplot* if it already running
  566. (with-current-buffer "*gnuplot*"
  567. (goto-char (point-max))))
  568. (org-plot/goto-nearest-table)
  569. ;; Set default options.
  570. (dolist (pair org-plot/gnuplot-default-options)
  571. (unless (plist-member params (car pair))
  572. (setf params (plist-put params (car pair) (cdr pair)))))
  573. ;; Collect options.
  574. (save-excursion (while (and (equal 0 (forward-line -1))
  575. (looking-at "[[:space:]]*#\\+"))
  576. (setf params (org-plot/collect-options params))))
  577. ;; collect table and table information
  578. (let* ((data-file (make-temp-file "org-plot"))
  579. (table (let ((tbl (org-table-to-lisp)))
  580. (when (pcase (plist-get params :transpose)
  581. ('y t)
  582. ('yes t)
  583. ('t t))
  584. (if (not (memq 'hline tbl))
  585. (setq tbl (apply #'cl-mapcar #'list tbl))
  586. ;; When present, remove hlines as they can't (currentily) be easily transposed.
  587. (setq tbl (apply #'cl-mapcar #'list
  588. (remove 'hline tbl)))
  589. (push 'hline (cdr tbl))))
  590. tbl))
  591. (num-cols (length (if (eq (nth 0 table) 'hline) (nth 1 table)
  592. (nth 0 table))))
  593. (type (assoc (plist-get params :plot-type)
  594. org-plot/preset-plot-types)))
  595. (unless type
  596. (user-error "Org-plot type `%s' is undefined." type-name))
  597. (run-with-idle-timer 0.1 nil #'delete-file data-file)
  598. (when (eq (cadr table) 'hline)
  599. (setf params
  600. (plist-put params :labels (car table))) ; headers to labels
  601. (setf table (delq 'hline (cdr table)))) ; clean non-data from table
  602. ;; Collect options.
  603. (save-excursion (while (and (equal 0 (forward-line -1))
  604. (looking-at "[[:space:]]*#\\+"))
  605. (setf params (org-plot/collect-options params))))
  606. ;; Dump table to datafile
  607. (if-let ((dump-func (plist-get type :data-dump)))
  608. (funcall dump-func table data-file num-cols params)
  609. (org-plot/gnuplot-to-data table data-file params))
  610. ;; Check type of ind column (timestamp? text?)
  611. (when (plist-get params :check-ind-type)
  612. (let* ((ind (1- (plist-get params :ind)))
  613. (ind-column (mapcar (lambda (row) (nth ind row)) table)))
  614. (cond ((< ind 0) nil) ; ind is implicit
  615. ((cl-every (lambda (el)
  616. (string-match org-ts-regexp3 el))
  617. ind-column)
  618. (plist-put params :timeind t)) ; ind holds timestamps
  619. ((or (string= (plist-get params :with) "hist")
  620. (cl-notevery (lambda (el)
  621. (string-match org-table-number-regexp el))
  622. ind-column))
  623. (plist-put params :textind t))))) ; ind holds text
  624. ;; Write script.
  625. (with-temp-buffer
  626. (if (plist-get params :script) ; user script
  627. (progn (insert
  628. (org-plot/gnuplot-script table data-file num-cols params t))
  629. (insert "\n")
  630. (insert-file-contents (plist-get params :script))
  631. (goto-char (point-min))
  632. (while (re-search-forward "\\$datafile" nil t)
  633. (replace-match data-file nil nil)))
  634. (insert (org-plot/gnuplot-script table data-file num-cols params)))
  635. ;; Graph table.
  636. (gnuplot-mode)
  637. (gnuplot-send-buffer-to-gnuplot))
  638. ;; Cleanup.
  639. (bury-buffer (get-buffer "*gnuplot*")))))
  640. (provide 'org-plot)
  641. ;; Local variables:
  642. ;; generated-autoload-file: "org-loaddefs.el"
  643. ;; End:
  644. ;;; org-plot.el ends here