- 追加された行はこの色です。
- 削除された行はこの色です。
#author("2019-11-07T09:26:43+00:00","","")
#author("2019-11-07T09:43:35+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">)
** 日本語対応 [#te98a037]
#html(<div style="padding-left: 10px;">)
#TODO
#html(</div>)
** 折れ線グラフの描画 [#zacf5ffd]
#html(<div style="padding-left: 10px;">)
#TODO
#html(</div>)
** 散布図の描画 [#qde44fee]
#html(<div style="padding-left: 10px;">)
#TODO
#html(</div>)
** ヒストグラムの描画 [#k14c4a4d]
#html(<div style="padding-left: 10px;">)
https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.hist.html
#mycode2(){{
import matplotlib.pyplot as plt
x = np.array([42, 32, 44, 43, 36, 14, 22, 35, 45])
plt.hist(x, range=[0, 50], bins=10)
plt.grid(True)
plt.show()
}}
*** ヒストグラムの正規化 [#u0d1dcdb]
#html(<div style="padding-left: 10px;">)
%%normed=1%% density=True を指定するとヒストグラムが正規化される。(binの面積の合計は1.0となる)
// μ = 0, σ2 = 1 である標準正規分布(1次元)のグラフを描いてみる。
#mycode2(){{
normal_data = np.random.normal(0, 1.0, 1000)
bins_num = 10
data_num = 1000
normal_data = np.random.normal(0, 1.0, data_num)
plt.hist(normal_data, bins=bins_num, density=True)
plt.grid(True)
plt.show()
}}
//# y軸のメモリを再計算()
//ax.yaxis.set_ticklabels(["{:0.2f}".format(i / (sum(hist_values) / data_num)) for i in ax.yaxis.get_ticklocs()])
目盛りを密度(パーセンテージ)で描画したい場合は、weight を調整するか、目盛りを再計算する。
#mycode2(){{
hist_weight = np.zeros(len(normal_data)) + 1 / len(normal_data) * 100
plt.hist(normal_data, bins=bins_num, weights=hist_weight)
}}
#html(</div>)
#html(</div>)
** 目盛りの設定 [#q7ebc060]
#html(<div style="padding-left: 10px;">)
#TODO
#html(</div>)
** グリッドの描画 [#od6e450a]
#html(<div style="padding-left: 10px;">)
#TODO
#html(</div>)
** 判例の描画 [#y044c7c9]
#html(<div style="padding-left: 10px;">)
#TODO
#html(</div>)
** 線の設定 [#p609ce4d]
#html(<div style="padding-left: 10px;">)
#TODO
#html(</div>)
** グラフを重ねる [#xad12c1a]
#html(<div style="padding-left: 10px;">)
#TODO
#html(</div>)
** 任意の位置に線を引く [#hd97127f]
#html(<div style="padding-left: 10px;">)
#TODO
#html(</div>)
** 任意の位置に文字を書く [#db59fdb4]
#html(<div style="padding-left: 10px;">)
#TODO
#html(</div>)
** 領域を分割して複数のグラフを描く [#ia539f4d]
#html(<div style="padding-left: 10px;">)
#TODO
#html(</div>)
#html(</div>)
// 使い方 END
* サンプル [#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']
plt.title("2019-08-01", size = 10, color = "black")
plt.suptitle("Load Average", size = 12, color = "black")
plt.xticks(np.arange(0, 144, 6), np.arange(0, 24))
plt.xlabel("時刻")
plt.ylabel("ロードアベレージ")
plt.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()
# 画像データを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>)