org-plot.el 26 KB

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