emacs org-mode の中で快適に python を操る。

python に愛がなくなって久しいけど、プログラマにとっての lingua franca は、python なので他のプログラマとのコミュニケーションとしてどうしても必要。みんなは jupyter を使うけど、それだと他のメモとか論文とかプログラムと離れてしまう。

https://github.com/doomemacs/doomemacs/issues/2416#issuecomment-577944200

まず、 venv をつくり、入れたいライブラリーを pip する。

python3 -m venv ~/venv/default
. ~/venv/default/bin/activate
pip install numpy
pip install pandas
pip install matplotlib

ここで、elisp で、どの python を使うか emacs に教えてあげる。

(setq org-babel-python-command "~/venv/default/bin/python")
~/venv/default/bin/python

ちなみに、この ~/venv/default/bin/python を ls で見ると、symlink なので、まさかいつも python をコピーしているわけではないから、安心して ok。

上の venv を毎回つくるのが面倒だと思うので、デフォルトでこの default venv を Doom Emacs config で設定した。でもいつも作る癖があるといいかもね。何も想定する必要がなくなるから。

import numpy as np
x = np.arange(3)
y = np.array([0.5, 0.1, 1.9])

とすることで、同じ session の中での計算が引き継がれる、jupyter 的なので実行はウォーターフォールなので、実行順は要注意なのかな。

y

このために、mac 側の rsync を brew で更新した。上にも書いたように再現性を担保したいのなら、

:tangle file_path でできたスクリプトの書き出し先を設定できる。

# import matplotlib.pyplot as plt
#
# fig, ax = plt.subplots()
# ax.bar(x,y)
path = '~/notes/images/python/test.png'
# plt.savefig(path)

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', '_red', 'orange']
bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']

ax.bar(fruits, counts, label=bar_labels, color=bar_colors)

ax.set_ylabel('fruit supply')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')

plt.savefig(path)
print("hi")

Date: 2023-09-05 Tue 13:40