LoginSignup
5
9

More than 5 years have passed since last update.

libsixelを使ってPythonでSixelを出力してターミナルにMatplotlibのグラフを出す。

Last updated at Posted at 2016-04-19

やること

libsixelにPython interfaceがあったので使ってみます。

インストール

省略。

やりかた

byte列からSixelデータに変換すれば良いのですが、それやろうとするとCのAPI使わなければならなそうだったので、実行時効率を捨てて手軽に実現します。

from libsixel.encoder import Encoder as SixelEncoder
from libsixel import SIXEL_OPTFLAG_WIDTH, SIXEL_OPTFLAG_HEIGHT
from tempfile import NamedTemporaryFile

def sixeldraw(width=None,height=None):
    with NamedTemporaryFile(prefix="sixel-") as fd:
        pl.savefig(fd,format="png")
        fd.flush()
        encoder = SixelEncoder()
        if width : encoder.setopt(SIXEL_OPTFLAG_WIDTH, width)
        if height: encoder.setopt(SIXEL_OPTFLAG_HEIGHT,height)
        encoder.encode(fd.name)

if __name__=="__main__":
    import matplotlib
    matplotlib.use("Agg")
    import pylab as pl
    import numpy as np
    x = np.linspace(0,1)
    y = x**2
    pl.plot(x,y)
    sixeldraw(640)

はい。一時的にファイル作ってグラフ画像を保存します。その画像ファイルをlibsixelのpython interfaceを使ってSixel形式で標準出力に出します。Sixel対応のターミナルを使ってれば画像がでます。

手抜き実装です。

5
9
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
9