fig = plt.figure() #Figureオブジェクトを作成。 ax = fig.add_subplot(111) #AxesSubplotオブジェクトの作成(プロットする領域)。 ax.plot([1,2,3]) #axにプロット fig.show() #表示
plt.figure(1) #省略可 plt.subplot(111) #省略可 plt.plot([1,2,3]) #アクティブなfigureとaxesに作用する。 plt.show()
plt.close() #カレントのfigureを閉じる plt.close('all') #全てのfigureを閉じるスクリプトで連続して複数の図を描くときは、メモリ消費を減らすため不要になったらclose()するようにする。
plt.ion()でインタラクティブモードに移行するか、ipythonの場合は
$ ipython -pylabで起動すればよい。
plt.figure(figsize=(横, 縦), dpi=解像度, facecolor=背景色)キャンバス(ウィンドウ)の大きさはインチ単位。デフォルトはfigsize=(8, 6)、dpi=80
plt.subplots_adjust(left=0.1, right=0.9)
left/right/top/bottom | subplotの左/右/下/上の位置 |
---|---|
wspace/hspace | subplotどうしの左右/上下の余白 |
top = fig.subplotpars.top wspace = fig.subplotpars.wspaceで取得できる。
import matplotlib as mpl mpl.rc('figure.subplot',left=0.08,hspace=0.05,wspace=0,bottom=0.05,top=0.92)元に戻すには、
mpl.rcdefaults()としてデフォルト値を再読み込みする。
plt.savefig('hoge.png', transparent=True)で透明にできる。ただしこれだとキャンパスだけでなくて図の未定義値とかの部分まで透明になるので、Axesオブジェクト以外のFigureを透明にするときは、
fig = plt.figure() fig.patch.set_alpha(0.)
from mpl_toolkits.axes_grid1 import ImageGrid fig = plt.figure() grid = ImageGrid(fig, 111, #figureとsubplotの引数でマルチプロットする枠を指定 nrows_ncols = (1, 3), #(行, 列)で分割数を指定 ) for i in range(3): #ImageGridはaxesのリストみたいになっているので個々の要素にプロットしていく。 ax = grid[i] ax.imshow(Z[i])
direction | 図をどの順にリストに配置するか。行方向優先('row')と列方向優先('column')を指定可能。デフォルトはrowでsubplotと同じ。 |
---|---|
axes_pad | 図の間隔(インチ)。デフォルトは0.05 |
add_all | |
label_mode | 軸目盛のラベルをどこにつけるか。すべての図('all')、左端と下端('L')、左下の図のみ('1') |
share_all | x軸とy軸をすべて共有するか |
cbar_location | カラーバーの位置 |
cbar_mode | それぞれの図のカラーバーを描くか。1つのカラーバーで代用('single')、それぞれの図に描く('each') |
cbar_size | |
cbar_pad |
best | 0 | upper right | 1 | upper left | 2 | lower left | 3 | lower right | 4 | right | 5 |
---|---|---|---|---|---|---|---|---|---|---|---|
center left | 6 | center right | 7 | lower center | 8 | upper center | 9 | center | 10 |
ax.legend(loc=1) ax.legend(loc='upper right')
shadow | 枠に影をつける |
---|---|
fancybox | 枠の角を丸くする |
frameon | 枠を描く |
title | 凡例につけるタイトル文字列 |
ncol | 凡例の列数 |
---|
numpoints | lineプロットの際のマーカーの数。デフォルトは2 |
---|---|
scatterpoints | scatterプロットの際のマーカーの数。 |
markerscale | 凡例の表示するマーカーの大きさ。実際の図のマーカーに対する相対的な大きさで指定 |
handlelength | lineの長さ |
handlelheight | lineの高さ |
handletextpad | 凡例の記号とラベルテキストとの余白 |
---|---|
borderaxespad | |
borderpad | |
columnspacing | 凡例が複数列の場合の間の余白 |
labelspacing | ラベル間の上下の余白 |
ax.legend(bbox_to_anchor=(1.05, 0), loc='bottom left', borderaxespad=0) #凡例の左下が(1.05, 0)になるように凡例の領域(axes)と実際に描画される枠線との間には一定の余白をとるようになっているのでborderaxespadをゼロにしないとbbox_to_anchorの座標ぴったりにはならない。
bbox_to_anchor | (x, y)または(x, y, 幅, 高さ)のタプルで指定。大きさは図の軸領域の縦、横を1としたときの大きさ、座標になる。 |
---|---|
bbox_transform | transAxesオブジェクトを与えることでbbox_to_anchorの基準座標、長さを変える |
borderaxespad | 凡例の領域境界と枠線との間の余白 |
ax=plt.gca() handles, labels = ax.get_legend_handles_labels() plt.legend(handles[::-1], labels[::-1])
fig = plt.figure() fig.suptitle("suptitle", fontweight="bold") ax = fig.add_subplot(111) ax.set_title("set_title") ax.set_xlabel("set_xlabel") ax.set_ylabel("set_ylabel") #または plt.title("title") plt.xlabel("xlabel") plt.ylabel("ylabel")
#座標系での位置で指定 plt.text(0.2,0.5,"text") plt.text(0.5,0.2,"text", fontsize=15, colot="red") #相対座標で指定する場合。図の枠の左下が(0,0)、右上が(1,1)になる。 plt.text(0.01, 1.01, "text", transform=ax.transAxes)
horizontalalignment/ha | 文字のどの位置を水平方向の基準にするか。‘center’、‘right’、‘left’がある。 |
---|---|
verticalalignment/va | 鉛直方向の基準位置。'center'、'upper'、'bottom'、'baseline' |
ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16, horizontalalignment='right', verticalalignment='bottom')この場合は、xycoordsで指定した基準座標で、xyの位置にテキストが描画される。もっと、細かい設定も可能である。参考
ax.annotate('Test', xy=(1, 0), xycoords='axes fraction', fontsize=16, xytext=(-5, 5), textcoords='offset points', ha='right', va='bottom')textcoords='offset points'を指定すると、xycoordsで指定した基準座標で、xyの位置にまず基準点を置いて、そこを (0,0)としたとき、xytextの位置にテキストが描画される。
xy | 位置。座標で指定。 |
---|
figure points | |
---|---|
figure pixels | |
figure fraction | |
axes points’ | |
axes pixels | |
axes fraction | axesを基準にして、(0,0)が左下、(1,1)が右上 |
data | |
offset points | xyで指定した位置を基準にした、相対的な座標をピクセル単位で指定 |
polar |
mathtext.fontset : stixsans #フォントfamilyをテキストのデフォルトと同じsans-selifにする。 mathtext.default : rm #数式フォントを\mathtextrm{}にする。デフォルトはイタリック
colors = cm.jet(np.arange(0,7.1,1))
plt.contourf(X, Y, Z, interval, colors=colors)
plt.axis([xmin,xmax,ymin,ymax]) #x,y軸の範囲を指定 plt.xlim([xmin,xmax]) #x軸の範囲 plt.ylim([ymin,ymax]) #y軸の範囲キーワードで指定することもできる。
off | 軸とラベルをオフにする。 |
---|---|
equal | x軸とy軸の1目盛りの図における長さが等しくなるように範囲を決める。 |
scaled | |
tight | データ長と同じにする。 |
plt.axis('tight')
plt.majorticks_on/off() # 主目盛りを表示する/しない plt.minorticks_on/off() # 補助目盛りを表示する/しない
plt.locator_params(axis='x',tight=True, nbins=4)キーワード
axis | 軸の指定('x', 'y', 'both') |
---|---|
tight | (True, False, None) |
nbins | intervalの数。メモリはnbins+1個になる。 |
---|---|
steps | |
integer | |
symmetric | |
prune |
from matplotlib.ticker import * ax = plt.gca() ax.xaxis.set_minor_locator(MultipleLocator(6)) #x軸主目盛り ax.xaxis.set_major_locator(MultipleLocator(24)) #x軸補助目盛り
plt.tick_params(axis='both')キーワード以下のようなものが指定可能。
axis | 書式を設定する軸。('x'、'y'、'both') |
---|---|
which | 書式を設定する目盛り。('major'、'minor'、'both') |
direction | 内向き('in')か外向き('out') |
length | 目盛りの長さ |
width | 目盛りの幅 |
color | 色 |
from matplotlib.ticker import FormatStrFormatter ax.xaxis.set_major_formatter(xmajorFormatter) #x軸主目盛 ax.yaxis.set_major_formatter(ymajorFormatter) #y軸主目盛 ax.xaxis.set_minor_formatter(xminorFormatter) #x軸補助目盛 ax.yaxis.set_minor_formatter(xminorFormatter) #y軸補助目盛Formatterには以下のようなものがある。いずれもmatplotlib.tickerのサブクラス。
NullFormatter | 目盛りなし |
---|---|
FixedFormatter | 同じ文字列をふる |
FuncFormatter | 引数を2つとる関数やlambda式を使って自分で設定 |
FormatStrFormatter | フォーマットをコードで指定 |
ScalarFormatter | |
LogFormatter |
from matplotlib.ticker import * ax.xaxis.set_majpr_formatter(FixedFormatter('abc')) #abcで固定 ax.yaxis.set_major_formatter(FormatStrFormatter('%.1f m/s')) #小数点以下一ケタでm/sを単位
def lon2txt(lon, pos=None): fmt = '%g' lon = (lon+360) % 360 if lon>180: lonlabstr = u'%s\N{DEGREE SIGN}W'%fmt lonlab = lonlabstr%abs(lon-360) elif lon<180 and lon != 0: lonlabstr = u'%s\N{DEGREE SIGN}E'%fmt lonlab = lonlabstr%lon else: lonlabstr = u'%s\N{DEGREE SIGN}'%fmt lonlab = lonlabstr%lon return lonlab lon = np.arange(0.,360.,2.5) time = np.arange(-10,11) plt.contour(lon,time,olr) plt.gca().xaxis.set_major_formatter(FuncFormatter(lon2txt)) plt.ylabel('Lag in Days') plt.xlim([100,270]) plt.show()
ax=plt.gca() ax.set_yscale('log') ax.yaxis.set_major_formatter(NullFormatter()) ax.yaxis.set_minor_formatter(FormatStrFormatter('%d')) ax.yaxis.set_minor_locator(FixedLocator([1000,850,700,500,400,300,200,150,100,70,50]))
import datetime from dateutil.relativedelta import * time = [datetime.date(2010,7,1) + relativedelta(days=i) for i in range(62)]matplotlibではその表示形式を操作する方法が提供されている。datesクラスのlocatorとformatterをaxisクラスのインスタンスに設定していく。
import matplotlib.dates as dates ax=plt.subplot(111) ax.xaxis.set_major_locator(dates.DayLocator(interval=10)) #主目盛を日単位で10日間隔で表示 ax.xaxis.set_minor_locator(dates.DayLocator(interval=5)) #補助目盛を日単位で5日間隔で表示 ax.xaxis.set_major_formatter(dates.DateFormatter('%d%b\n%Y')) #主目盛のラベルの表示形式を指定
AutoDateLocator |
---|
NullLocator | |
---|---|
FixedLocator | |
IndexLocator | |
LinearLocator | |
LogLocator | |
MultipleLocator | |
MaxNLocator | |
AutoLocator | |
AutoMinorLocator |
$ cp /usr/local/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc ~/.matplotlib/matplotlibrc