Skip to content

Instantly share code, notes, and snippets.

@nakagami
Last active September 21, 2024 15:10
Show Gist options
  • Save nakagami/709e87c1f7c4da2f02583c81a24d5350 to your computer and use it in GitHub Desktop.
Save nakagami/709e87c1f7c4da2f02583c81a24d5350 to your computer and use it in GitHub Desktop.
matplotlib and libsixel draw fig to terminal
# https://qiita.com/bjam_ha_nai/items/609924c91343a12d6769
# sudo apt install libsixel-bin libsixel-dev
# pip install libsixel-python matplotlib
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
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:
plt.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)
def plot():
matplotlib.use("Agg")
x = np.linspace(0, 1)
y = x**2
plt.plot(x, y)
sixeldraw()
if __name__ == "__main__":
plot()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment