文書の過去の版を表示しています。
Python モジュール: matplotlib
概要
- Python でグラフを描画するためのモジュール
使い方
モジュールの読み込み
import matplotlib.pyplot as plt
- 同時に
numpyも読み込んでおくと良い。 - Ubuntu の場合は、
python-tkやpython3-tkが必要なので、インストールしておく。
$ sudo apt install python-tk python3-tk
グラフの描画
- データを定義する。
- x, y をリスト形式で定義する。
例:x = [1,2,3,4] y = [5,6,7,8]
- グラフを描画する。
plt.plot(x, y, PLOTSTYLE [, x2, y2, PLOTSTYLE2, ...], label = LABEL)
x,y: 描画するデータPLOTSTYLE: プロットの形式を指定 (以下の記号を文字列として組み合わせる)-: 実線 (solid line)|--: 破線 (dash line)|-.: 点線と破線 (dash-dot line)|:: 点線 (dotted line).: 小さめの丸 (point marker),: 点 (pixel marker)o: 丸 (circle marker)v: 下三角 (triangle_down marker)^: 上三角 (triangle_up marker)<: 左三角 (triangle_left marker)>: 右三角 (triangle_right marker)1: (tri_down marker)2: (tri_up marker)3: (tri_left marker)4: (tri_right marker)s: 四角形 (square marker)p: 五角形 (pentagon marker)*: アスタリスク (star marker)h: 六角形 (縦方向) (hexagon1 marker)H: 六角形 (横方向) (hexagon2 marker)+: + (plus marker)x: ×(x marker)D: ダイア (四角形が 45 度傾いたマーク) (diamond marker)d: ダイア (細長いダイア) (thin_diamond marker)|: 縦棒 (vline marker)_: 横棒 (hline marker)b: 青g: 緑r: 赤c: シアンm: マゼンタy: 黄色k: 黒w: 白
LABEL: 描画する線の名前- 複数のデータをプロットする場合は、それぞれのデータ (線、プロット) について、plot() を実行する。
- グラフの設定をする。
plt.xlabel(LABEL): x 軸の名前をLABELで指定する。plt.ylabel(LABEL): y 軸の名前をLABELで指定する。plt.legend(loc = “best”): 凡例の位置を最適 (best) な位置に配置する。- その他の位置
+-----------+ |2 9 1| | | |6 10 5,7| | | |3 8 4| +-----------+
0orbest1orupper right2orupper left3orlower left4orlower right5orright6orcenter left7orcenter right8orlower center9orupper center10orcenter
- グラフを表示する。
plt.show()
- グラフを閉じる。
plt.close()
- グラフを消す場合は
plt.cla()やplt.clf()を使う。
その他のグラフの設定
plt.grid(b = BOOL, which = TARGET, axis = AXIS): グリッド線の設定BOOL: グリッドの表示の有無 (True: 表示 /FalseorNone: 非表示)TARGET: 設定する対象 (major: 主目盛線 /minor: 補助目盛線)AXIS: グリッド線の方向 (both: 両方 /x: X 軸 /y: Y 軸)- その他のオプション
linestylecolor
- 描画範囲の設定
plt.xlim(X0, X1) plt.ylim(Y0, Y1)
X0,Y0: X および Y の描画開始位置X1,Y1: X および Y の描画終了位置
- フォントの調整: matplotlibで日本語 - Qiita
Tips
ipython でグラフを閉じた後に操作を受け付けない
- 対話操作が可能なようにする。
plt.interactive(True)
or
plt.ion()
Qt に関する ImportError
- 以下のエラーが出る。
ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5, PySide or PySide2 package to be installed, but it was not found.
- Qt を使わないようにする。
- 直接設定する場合
import matplotlib matplotlib.use('TkAgg')
- 設定ファイルで設定する場合
backend : qt5agg
↓
backend : Tkagg
- 参考サイト: