matplotlib
- プロットの基本設定
- 線を描く
- コントア
- box/bar を描く
- 誤差棒(エラーバー)の表示
- ヒストグラム
- 複数の2Dヒストグラムの表示
- 2Dヒストグラムを3D表示にしたい
- 図の微調整
- 特定の目盛だけ表示したい
- subplot環境下でカラーバーを表示したい
- プロットの基本設定
- フォント
- デフォルトでは5種類用意されている
- serif: ロマン体。文字のはじが伸びていたりする (ex Times, Century)
- sans-serif: サンセリフ。セリフのない字体 (ex Arial, Helvetica, Gill Sans)
- cursive: 筆記体みたいな字体 (ex Zapfino)
- fantasy: 装飾文字 (ex Western)
- monospace: 等幅文字 (ex Courier)
- デフォルトでは5種類用意されている
- フォント
text(10, 7, 'serif', fontsize=23, fontname='serif')
text(10, 6, 'sans-serif', fontsize=23, fontname='sans-serif')
text(10, 5, 'cursive', fontsize=23, fontname='cursive')
text(10, 4, 'fantasy', fontsize=23, fontname='fantasy')
text(10, 3, 'monospace', fontsize=23, fontname='monospace')
# text 文字入力関数
# (文字の始まるx座標, y座標, '入力したい文字', fontsize=fontの大きさ, fontname='font名')
xlabel('x-axis', fontname='fantasy', fontsize=20)
ylabel('y-axis', fontname='cursive', fontsize=20)
# xlabel x座標軸の表記
# ('座標軸の名前等', fontname='font名', fontsize=fontの大きさ). ylabelも同じ
#!/usr/local/bin/python
#-*- coding: utf-8 -*-
# 文字コードの宣言。 特に日本語を入力したい場合は必須
# 入れなかった場合のエラーは以下
SyntaxError: Non-ASCII character '\xe3' in file plot.py on line 47, but no encoding declared;see http://www.python.org/peps/pep-0263.html for details
from matplotlib.pyplot import *
from matplotlib.font_manager import *
# フォントを設定するためのパッケージの読み込み
mw = matplotlib.font_manager.FontProperties(fname='~/Library/Fonts/MilkyWell.ttf')
jp = matplotlib.font_manager.FontProperties(fname='/Library/Fonts/osaka.ttf')
# 使用したいフォントの指定
text(10, 6, 'milky well', fontsize=50, fontproperties=mw)
text(10, 4, u'おおさかフォント', fontsize=40, fontproperties=jp)
# 日本語を出力したい場合は 出力したい文字列の前に"u"を必ず入れる
# u 以下に続く文字列はunicode型ですよ, という宣言をしている
# これを忘れると以下のエラーが出る
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128)
savefig('2013_10_31.png')
# 日本語フォントはinteractionモードでは表示されないらしい
# 画像として出力
- フォントの埋め込み
- Matplotlibでは基本的にはフォントは全てアウトライン化されて出力されるが、PDF形式なら埋め込める
from matplotlib.pyplot import *
from matplotlib.figure import *
rcParams['pdf.fonttype'] = 42
# PDFにフォントを埋め込むためのパラメータ。スクリプトの最初に設定
# 埋め込みできるTrue Type Font (Type42) を指定
- 座標軸の調整
- 以下のパラメーター設定をスクリプトの一番最初に書いておけばよい
- ※ 例の図ではx軸の目盛の長さが長くなっている(xticks=20にしているので)
- 以下のパラメーター設定をスクリプトの一番最初に書いておけばよい
params = {
'font.family' :'serif', # フォントを指定
'axes.fontsize' :16, # 軸の目盛文字の大きさを指定
'axes.labelsize' :28, # 軸のラベル文字の大きさを指定
'xtick.labelsize':28, # x軸のラベル文字の大きさを指定
'ytick.labelsize':28, # y軸のラベル文字の大きさを指定
'legend.fontsize':16, # legendの文字の大きさを指定
'xtick.major.size':20, # x軸主目盛の長さを指定
'xtick.minor.size':6, # x軸副目盛の長さを指定
'ytick.major.size':10, # y軸主目盛の長さを指定
'ytick.major.size':6 # y軸副目盛の長さを指定
}
plt.rcParams.update(params)
# 上で指定したパラメーターをスクリプト内に適用させる一言
- markerの種類
- 基本は以下(なぜかオクタゴンは表示されず。。)
- 以下の基本形を組み合わせて自分でmarkerを作られるらしいが、勉強中なので後日
plot(1,5, ms=20., marker='.', label='point')
plot(2,5, ms=20., marker=',', label='pixel')
plot(3,5, ms=20., marker='o', label='circle')
plot(4,5, ms=20., marker='v', label='triangle_down')
plot(5,5, ms=20., marker='^', label='triangle_up')
plot(6,5, ms=20., marker='<', label='triangle_left')
plot(7,5, ms=20., marker='>', label='triangle_right')
plot(1,4, ms=20., lw=2, marker='1', label='tri_down')
plot(2,4, ms=20., lw=2, marker='2', label='tri_up')
plot(3,4, ms=20., lw=2, marker='3', label='tri_left')
plot(4,4, ms=20., lw=2, marker='4', label='tri_right')
plot(5,4, ms=20., marker='8', label='octagon')
plot(6,4, ms=20., marker='s', label='square')
plot(7,4, ms=20., marker='p', label='pentagon')
plot(8,4, ms=20., marker='*', label='star')
plot(1,3, ms=20., marker='h', label='hexagon1')
plot(2,3, ms=20., marker='H', label='hexagon2')
plot(3,3, ms=20., marker='+', label='plus')
plot(4,3, ms=20., marker='x', label='x')
plot(5,3, ms=20., marker='D', label='diamond')
plot(6,3, ms=20., marker='d', label='thin_diamond')
plot(7,3, ms=20., lw=2, marker='|', label='vline')
plot(8,3, ms=20., lw=2, marker='_', label='hline')
# marker=' ' で使いたいmarkerを指定
# plot( )ではmarkerのサイズは ms= で指定するが、scatter( )の場合は s= で指定する
- 色
- htmlの色も使える(参照)
plot(1,5, ms=30., marker='o', c='b', label='Blue')
plot(2,5, ms=30., marker='o', c='r', label='Red')
plot(3,5, ms=30., marker='o', c='#ff00ff', label='#ff00ff')
# c=' ' で使いたい色を指定
# デフォルト以外はhtmlの色指定と同じ方法で色を選択できる
scatter(4,5, s=30., marker='o', c='g', edgecolor='g', label='size 30 EC=g')
# markerのふちの色も指定したい時は edgecolor=' ' で指定できる(デフォルトは黒)
# ただし、edgecolorが指定できるのは scatter( ) の時のみ
# edgecolor=' ' の太さは lw= (linewidthの意味)で指定できる
# おまけ:plot( ) と scatter( ) の時では同じmarker sizeを指定しても表示される大きさは異なる
scatter(5,5, s=500., marker='o', c='g', edgecolor='m', lw=3, label='size 500 EC=m')
- 線を描く
- 2点間を結ぶ直線
plot([3,5],[5,5])
# 水平の青線。([xmin, xmay],[ymin, ymax]) を表す
# (xmin, ymin)→(xmax, ymax)の間の線をひいてくれる
plot([6,6],[2,7]) # 垂直の緑線
plot([2,7],[3,7]) # 斜め赤線
axhline(2, ls=':') # y=** の線
axvline(2, ls='-.') # x=** の線
- 様々な線の種類
axhline(2, ls=':', lw=3.) # ドット
axhline(4, ls='-', lw=3.) # 直線
axhline(6, ls='--', lw=3.) # ダッシュ
axhline(8, ls='-.', lw=3.) # ダッシュ+ドット
# ls は line style の事で、線の種類を指定
# lw は line width の事で、線の太さを指定
- コントア
- 散布図の上に描く
- データ点の2Dヒストグラムの値をもとにコントアにする
- arange の bin のサイズ。(左)0.05、(右)0.1にした場合
- 散布図の上に描く
scatter(x,y,marker='o',s=10.,c='c',alpha=0.4) # 散布図
x_range = arange(0.0,3.1,0.1) # x軸メッシュの(min, max, bin)
y_range = arange(-3.0,0.1,0.1) # y軸メッシュの(min, max, bin)
his, xhis, yhis = histogram2d(x, y, bins=(31,31),range=((0.0,3.0),(-3.0,0.0)))
# binsはメッシュの数。range と bins は arange と合わせる
# 2Dヒストグラムのパラメータ
xx, yy = meshgrid(x_range,y_range)
# xx, yyに、x, yを2次元に変換した配列を代入。ちなみにx, yは1次元の配列
con = contour(xx, yy, his.transpose(), 4, linewidths=1.5, colors='black')
# コントア作画時のパラメーター。transpose( ) は転置
# contour(x, y, 2Dヒストグラム(x, y)に位置するbin内の点数, コントア数)
- コントア内を塗る
- (左)方法[1]、(右)方法[2]
方法[1]
contourf(xx, yy, his.transpose(), 4, linewidths=1.5, colors=('w','b','g','yellow','r'), alpha=0.5)
# colors=('背景色', 'lower level', ..., 'higher level') で色を指定
方法[2]
pcolor(xx, yy, his.transpose(), shading='flat')
colorbar()
cool()
# colorbar() でカラーバー表示。cool() は色の種類(参照)
- box/bar を描く
- 水平な box/bar
broken_barh([ (180, 70), (266, 89), (320, 100), (600, 100)] , (12,3), facecolors=('#00ff00','#5f9ea0','cyan','#87ceeb'), edgecolor='red')
# 水平barを描く基本形。broken_barh が水平方向のbarを描く関数
# ([(xの位置, x方向の長さ)], (yの位置, y方向の長さ)) を指定
# edgecolor、linestyle、linewidth は bar 外縁部の色、種類、太さを指定
broken_barh([ (85, 20), (215, 55) ], (2,3), facecolors=('yellow','green'))
# facecolors は bar そのものの色を指定
broken_barh([ (80, 36), (129, 45), (201, 66) ] , (7,3), facecolors=('yellow','#8b4513','green'), line'dashed', linewidth=6.)
# barの外枠の線種を変えて太くした場合
broken_barh([(2.5,2), (5,2)], (9,0.5), facecolor='g') # 図中2つ続きの横box
broken_barh([(5,4)], (5,3), facecolor='b') # 図中横box
axhspan(4, 1, facecolor='b', alpha=0.5) # 図中横bar。(yの上限値, yの下限値, facecolor='色', alpha=透過率)を指定
axvspan(2, 1, facecolor='r', alpha=0.5) # 図中縦bar。(xの位置, barの太さ, facecolor='色', alpha=透過率)を指定
broken_barh([(3,1)], (3,4), facecolor='r') # 図中縦box
- 垂直な box/bar
bar(1, 3, width=0.5)
bar(5, 6, width=0.5, bottom=-2.)
bar(8, 2, width=0.5, bottom=6.)
# 図を縦に走るbarを描く関数.
# (xの左側位置, barの長さ, width=太さ, bottom=barのyminの値)を指定
# bottomのデフォルトは bottom=0 ぽい
- 誤差棒(エラーバー)の表示
- +とーで異なる長さのエラーバーをつけたい
errorbar(x,y,yerr=[y_er*100,y_er],fmt='bo') # yerr=[-, +]のerrorbar
yscale("log",nonposy='clip') # -のerrorbarが負の値を含む場合のおまけ
- ヒストグラム
- 複数の2Dヒストグラムの表示
- 複数の線を重ねて表示
- 複数の2Dヒストグラムの表示
hist((a_ew, b_ew, d_ew, e_ew), bins=10.,range=(0,200), color=('b','g','orange','r'), histtype='step',lw=2)
# hist( )はヒストグラム用の関数。中のパラメーターは以下。
# a_ewとか:ヒストグラムで使いたいデータ列。複数の場合は (a_ew,b_ew,...)と( )でくくればok。
# bins:データ列を分割する数。
# range=(d_min, d_max):データの一部をヒストグラムに使いたい場合、指定する幅。
# range を指定した場合は、その範囲内で bins で分割される。
# histtype:ヒストグラムの種類を指定。step は線のみタイプ。
# lw:linewidthの意味。線の太さを指定。
- 透かし着色したヒストグラムを重ねて表示
hist((a_ew, b_ew, d_ew, e_ew), bins=10.,range=(0,200), color=('b','g','orange','r'), ec='none', histtype='stepfilled', alpha=0.3)
# histtype:stepfilled は着色ヒストグラムのこと。
# alpha:透明度を指定。1 は透明度0のこと。
- 各ヒストグラムを重ねて表示
hist((a_ew, b_ew, d_ew, e_ew), bins=10.,range=(0,200), color=('b','g','orange','r'), ec='none', histtype='barstacked')
# histtype:barstacked は重ねヒストグラムのこと。
- 細いbarを少しずつずらして表示
common_params = dict(bins=10, range=(0,200), color=('b','g','orange','r'), ec='none')
hist((a_ew, b_ew, d_ew, e_ew), **common_params)
# common_params に共通パラメーターをいれる。ec は edgecolor のこと。
hist((a_ew, b_ew, d_ew, e_ew), bins=10.,range=(0,200), color=('b','g','orange','r'), ec='none', histtype='bar')
# こちらの方法でも全く同じプロットができる。
# histtype:bar はbar状のプロット。
- 2Dヒストグラムを3Dにして表示
from mpl_toolkits.mplot3d import Axes3D # 3Dのモジュールを読み込む
ya,xa,pax = hist(a_ew, bins=20., range=(0,200), histtype='stepfilled')
yb,xb,pbx = hist(b_ew, bins=20., range=(0,200), histtype='stepfilled')
yc,xc,pcx = hist(c_ew, bins=20., range=(0,200), histtype='stepfilled')
yd,xd,pdx = hist(d_ew, bins=20., range=(0,200), histtype='stepfilled')
ye,xe,pex = hist(e_ew, bins=20., range=(0,200), histtype='stepfilled')
# hist関数内の "y*=データ列" "x*=bin" "p*=パラメーター" を変数にする。
# この変数の指定は図の書式設定の前に書かないとだめ!
fig1 = plt.figure(figsize=(10,10))
ax1 = fig1.add_subplot(111,projection='3d')
# 図の書式設定。projection='3d' で3Dの図にするという指定になっている。
for yy, zz, c in zip([ya,yb,yc,yd,ye], [5.,4.,3.,2.,1.]['b','g','#00ff00','orange','r']):
x=np.arange(0,200,10)
ax1.bar(x, yy, zs=zz, width=10, zdir='y', color=c, ec='w', alpha=0.6)
# bar( ): 棒グラフの表示。
# x:棒グラフのbinの位置。
# yy:xに入る数。
# zs:z方向の位置。
# width:棒グラフの幅。
# zdir:z方向のパラメーターを何にするかを指定。例では yy をz方向のパラメーターに設定している。
ax1.view_init(30,-92) # 初期表示の際の3Dの (仰角, 方位角) を指定。
ax1.set_ylim3d(0,6) # y方向の幅を指定。3dなので、ylim3d(min, max)。