UP | HOME

emacs-调用matplotlib画图,并存储到Windows的临时文件夹中

[2024-04-07 周日 10:13]

根据已有表格绘图,在表格上方标注名称,如:

#+NAME: myTimeTable
|1|2|
|-+-|
|3|4|

在python代码行的header里传入表格数据(在我用的org 9.6.14中数据会自动去除标题行和分割行,只剩下面的数据行):

#+begin_src python :results file link :var data=myTimeTable
import os,matplotlib, numpy
……

savedir = os.getenv('TEMP')+'\\myTimeTable.png'
plt.savefig(savedir)
return savedir

会把代码块上方的name动态传入到代码中

#+name: 代码块name
#+begin_src python :var filename=(org-element-property :name (org-element-context)) :results file link
import os,matplotlib, numpy
……
savedir = os.getenv('TEMP')+'\\'+filename+'.png'
plt.savefig(savedir)
return savedir

运行后会在下方生成

#+RESULTS:
file:..../XXX.png

的图片,可以配合inline 图片相关函数使用

;; (setq org-startup-with-inline-images t)
;;; Only display inline images under current subtree.
(defun org-display-subtree-inline-images (&optional state)
  "Toggle the display of inline images under current subtree.
INCLUDE-LINKED is passed to `org-display-inline-images'."
  (interactive)
  (save-excursion
    (save-restriction
      (org-narrow-to-subtree)
      (let* ((beg (point-min))
             (end (point-max))
             (image-overlays (cl-intersection
                              org-inline-image-overlays
                              (overlays-in beg end)))
             (display-inline-images-local
              (lambda ()
                (org-display-inline-images t t beg end)
                (setq image-overlays (cl-intersection
                                      org-inline-image-overlays
                                      (overlays-in beg end)))
                (if (and (org-called-interactively-p) image-overlays)
                    (message "%d images displayed inline"
                             (length image-overlays)))))
             (hide-inline-images-local
              (lambda ()
                (org-remove-inline-images)
                (message "Inline image display turned off"))))
        (if state
            (pcase state
              ('subtree
               (funcall display-inline-images-local))
              ('folded
               (funcall hide-inline-images-local)))
          (if image-overlays
              (funcall display-inline-images-local)
            (funcall hide-inline-images-local)))))))

(define-key org-mode-map (kbd "C-c C-x C-v") 'org-display-subtree-inline-images)

;;; auto display inline images on Org TAB cycle expand headlines.
(add-hook 'org-cycle-hook #'org-display-subtree-inline-images)
(add-hook 'org-babel-after-execute-hook 'org-redisplay-inline-images)

参考:https://emacs-china.org/t/org-link/13502/6

1. 通过代码块引用的方式重复使用部分代码

在代码块上方加上 #+NAME: line-plot ,然后在需要引用的代码块上加上 :noweb yes 参数,再在内部通过 <<pie-plot>> 的方式即可复用代码。

▲ 编辑于 [2024-05-22 周三 21:58] | © Published by Emacs 31.0.50 (Org mode 9.7.16) on [2024-11-21 周四 00:22] | RSS