Remrinのpython攻略日記

python3に入門しました。python3についてあれこれとサンプルコードとか。

matplotlibで図形

matplotlibで図形を描く方法。
 
plot()関数が呼ばれると背後でfigure()が呼ばれ、続いてaxes()が呼ばれてfigureの中に軸をつくる。
plot()関数を呼ばずにfigure()やaxes()で図、軸を設定できる。
 

import matplotlib.pyplot as plt

c1 = plt.Circle((0, 0), radius=1, fc="yellow", ec="r")
ax = plt.gca()
ax.add_patch(c1)
plt.axis("scaled")
plt.show()

 
f:id:rare_Remrin:20170506162014p:plain
 
○figure()関数
Figureオブジェクトを作る。
Definition :

figure(num=None,           # autoincrement if None, else integer from 1-N 
       figsize=None,       # defaults to rc figure.figsize 
       dpi=None,           # defaults to rc figure.dpi 
       facecolor=None,     # defaults to rc figure.facecolor 
       edgecolor=None,     # defaults to rc figure.edgecolor 
       frameon=True, 
       FigureClass=Figure, 
       **kwargs)

 

num figure番号。整数または文字列のオプション引数でデフォルトはNone。もしnumが与えられなければ、新しいfigureを作り、figure番号を1増やす。figureオブジェクトはこの番号をnumber属性として保持する。もしnumが与えられ、すでに存在しているfigure番号だった場合は、そのfigureオブジェクトをアクティブにし、参照を返す。存在しないfigure番号のときは、新規のfigureオブジェクトを作成し、その参照を返す。numが文字列のときはウィンドウのタイトルがnumになる。
figsize (幅, 高さ)の整数のタプルで単位はインチ。デフォルトはrc figure.figsize
dpi figureの解像度。整数で、デフォルトははrc figure.dpi
facecolor 背景色。デフォルトはrc figure.facecolor
edgecolor 枠の色。デフォルトはrc figure.edgecolor

 

返り値 figureオブジェクト

 
○axes()関数
 Figureオブジェクトに座標軸を付け加える

parameter 内容
facecolor color 軸の背景色
frameon True or False 枠を表示するか
sharex otherax 他の軸とxaxis属性を共有するか
sharey otherax 他の軸とyaxis属性を共有するか
polar True, False 極座標を使うか
aspect "equal", "auto", num アスペクト比x/y。"equal"は1:1

 
○axis()メソッド
素数4のタプルを引数としてaxis()メソッドを呼ぶと、座標軸の範囲を変更できる。

引数 内容
なし 現在の座標軸の範囲を(xmin, xmax, ymin, ymax)のタプルで返す。
"off" 座標軸を表示しない
"equal" 円が円に見える。
"scaled" 座上軸の両端の自動調整
"tight" 余白を小さく?
"image" データの範囲に合わせる
"auto" 非推奨
"normal" 非推奨
"square" x軸の範囲(xmax-xmin)とy軸の範囲を等しくする

 

fig = plt.figure()
ax =plt.axes()
print(plt.axis())   # (0.0, 1.0, 0.0, 1.0)

v = (0, 2, 0, 3)
plt.axis(v)
plt.show()

 
x軸の範囲が0~2、y軸の範囲が0~3になっている。
f:id:rare_Remrin:20170506155223p:plain

gcf()関数:現在のFifureへの参照。オブジェクトがない場合は作成する。
gca()関数:現在のAxesへの参照。オブジェクトがない場合は作成する。
 
○ax.set_aspect()関数
 グラフのアスペクト比を設定する。

○円plt.Circle以外にもいろいろな図形が書ける。
 Ellipse, Polygon, Rectangleなどなど
 
参考:
patches — Matplotlib 2.0.1 documentation