目次

概要

Pythonのグラフ描画ライブラリ Matplotlib の覚え書き。

インストール

pip install matplotlib

使い方

タイトルを設定する

TODO:

X/Y軸のメモリ幅を設定する

TODO:

X/Y軸のメモリラベルを設定する

TODO:

グラフ画像をファイルに出力する

TODO:

グラフ画像のバイナリデータを取得する

TODO:

サンプル

サーバーのロードアベレージの時系列データをグラフ描画してみる。

サンプルデータ
filesample_loadaverage.csv

sample.py

# coding: utf-8

import io
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import base64


def main():

  df = pd.read_csv("sample_loadaverage.csv")

  # 日本語フォントを利用可能にしておく
  plt.rcParams['font.sans-serif'] = ['Hiragino Maru Gothic Pro', 'Yu Gothic', 'Meirio', 'Takao', 'IPAexGothic', 'IPAPGothic', 'Noto Sans CJK JP']

  fig, ax = plt.subplots() # Figureオブジェクトとそれに属する一つのAxesオブジェクトを同時に作成

  #plt.xlim(xmin, xmax)
  ax.set_xticks(np.arange(0, 144, 6))
  ax.set_xticklabels(np.arange(0, 24))
  ax.set_title("2019-08-05", size = 10, color = "black")
  fig.suptitle("Load Average", size = 12, color = "black")
  ax.set_xlabel("時刻")
  #ax.set_ylabel("Load average")
  ax.set_ylabel("ロードアベレージ")

  ax.plot(df["datetime"], df["load-average01"])

  # そのまま描画(jupyter notebook 等の場合)
  plt.show()

  # ファイルに出力
  plt.savefig("sample_loadaverage.png")

  # 画像データを取得
  buff = io.BytesIO()
  plt.savefig(buff, format="png")
  plt.close(fig)

  # 画像データをbase64エンコードしてHTMLに出力.
  with open("sample_loadaverage.html", "w") as f:
    encoded_image = base64.b64encode(buff.getvalue()).decode("utf-8")
    f.write("<!doctype html>")
    f.write("<html>")
    f.write("<meta charset='utf-8'>")
    f.write("<img src='data:image/png;base64," + encoded_image + "' />")
    f.write("</html>")

if __name__ == "__main__":
  main()

結果

sample_loadaverage.png


トップ   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS