Nick George
Science Programming

Using python in org-mode

First published: August 27, 2017
Last updated: July 12, 2021

> Contents

Purpose

I have become accustomed to doing my exploratory data analysis in the awesome Jupyter notebooks, which are amazing tools. However, I am using Emacs org-mode for virtually everything I do on the computer now and I figured it was time to move my analysis here too.

Alternatives

I love the idea of ob-ipython, but after a few hours of work I keep getting an http parsing error and no output so I gave up.

Snippets

YASnippet for plotting session setup

# -*- mode: snippet -*-
# name: preplot
# key: preplot
# --
#+BEGIN_SRC python :session ${1:new} :results silent
  import os
  import matplotlib
  matplotlib.use('Agg')
  import matplotlib.pyplot as plt
   if not 'img' in os.listdir("."):
      os.mkdir('img')
#+END_SRC

rendered:

  import os
  import matplotlib
  matplotlib.use('Agg')
  import matplotlib.pyplot as plt
  if not 'img' in os.listdir("."):
      os.mkdir('img')

Plotting snippet

# -*- mode: snippet -*-
# name: plot
# key: plot
# --
#+BEGIN_SRC python :session ${1:new} :results drawer :exports both
$0
print(plt.savefig('img/$2.png'))
#+END_SRC

Looks like this:


  print(plt.savefig('img/fig.png'))

I intend to explore John Kitchin's pysce module more (demo here), but for now these snippets will do!