#author("2019-08-29T11:37:57+00:00","","")
#author("2019-09-01T12:14:26+00:00","","")
#mynavi(Python覚え書き)
#setlinebreak(on);

* 目次 [#o6e637f2]
#contents
- 参考
-- https://matplotlib.org/
-- [[Matplotlib が PC で追加のフォントをインストールしなくても日本語を表示できるようになった:https://qiita.com/yniji/items/2f0fbe0a52e3e067c23c]]
-- [[早く知っておきたかったmatplotlibの基礎知識、あるいは見た目の調整が捗るArtistの話:https://qiita.com/skotaro/items/08dc0b8c5704c94eafb9]]

- 関連
-- [[Python]]
-- [[Python覚え書き]]
-- [[numpy入門]]
-- [[pandas入門]]

* 概要 [#ubd317a3]
#html(<div style="padding-left:10px">)
Pythonのグラフ描画ライブラリ Matplotlib の覚え書き。
#html(</div>)

* インストール [#na833a68]
#html(<div style="padding-left:10px">)
#myterm2(){{
pip install matplotlib
}}
#html(</div>)

* 使い方 [#r8b777f2]
#html(<div style="padding-left:10px">)

** タイトルを設定する [#s0ebe6a4]
#html(<div style="padding-left:10px">)
#TODO
#html(</div>)

** X/Y軸のメモリ幅を設定する [#q4d3681f]
#html(<div style="padding-left:10px">)
#TODO
#html(</div>)

** X/Y軸のメモリラベルを設定する [#odb94ce9]
#html(<div style="padding-left:10px">)
#TODO
#html(</div>)

** グラフ画像をファイルに出力する [#dc02d118]
#html(<div style="padding-left:10px">)
#TODO
#html(</div>)

** グラフ画像のバイナリデータを取得する [#u198a1ad]
#html(<div style="padding-left:10px">)
#TODO
#html(</div>)

#html(</div>)


* サンプル [#hf0becef]
#html(<div style="padding-left: 10px">)

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

サンプルデータ
&ref(sample_loadaverage.csv);

sample.py
#mycode2(){{
# 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()
}}

** 結果 [#o8edbe1f]
&ref(sample_loadaverage.png);


#html(</div>)


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