FrontPage/Python/Scipy+Numpy

ドキュメント

→公式リファレンス

→docs

→User's Guide

→Beginner’s Guide

→Advanced Guide

モジュールのインポート

Matplotibを使ってグラフ描画するスクリプトは、PySideへそのまま移植したいと思っているので、pylabは使わず、pltとnpを使っていく.

import matplotlib.pyplot as plt
import numpy as np

webアプリケーションとしてグラフを保存する

多くの初心者は、Matplotlibをwebアプリケーションサーバで利用するときにエラーが出て困っている。なぜなら、MatplotlibはGUIで使う事を前提としており、X11への接続が必要になるからである。しかし、Webサーバーでも簡単なおまじないで使う事はできる。matplotlib.pyplotを呼び出す前にmatplotlib.use('Agg')を宣言するのだ。これで、matplolibはバックエンドでのみ動作し、GUIを必要とせずグラフを描画する事ができる。

→How-To-Matplotlib-Figure

# do this before importing pylab or pyplot
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3])
fig.savefig('test.png')

axes

ax = fig.add_subplot(1,1,1)
ax = fig.add_axes([0.15, 0.1, 0.7, 0.3]) : [left, bottom, width, height]
xtext = ax.set_xlabel(' frequency')
ytext = ax.set_ylabel(' Amplitude')
for ax in fig.axes:
    ax.grid(True)

fiugre, axes

plt.close('all')
fig, ax = plt.subplots()

→Artist

fig.tight_layout()

subplotの中身について、tickables, axis, labels, titlesの大きさを、タイトなレイアウトにしてくれる

→Tight Layout guide

s-tight_layout0.jpg
s-tight_layout1.jpg

Contour

pyplot.contour

contour(Z)
contour(Z, corner_mask=False, colors=(mpl_colors),  alpha = (float), cmap=Colormap, NORM=Normalize, vmin=scalar, vmax=scalar, levels=[float], origin=['upper'|'lower'|'image'], extent=(x0,x1,y0,y1), locator=?, extend=補完?
contour(Z, cmap='hot')

Colormap

pyplot.Colormap

mpl_cmap.png

→ Documenting the matplotlib colormaps

matplotlib.specgram

ガボールウェーブレットの結果をスペクトログラムの様に表示したいが、imshow()だと、縦横比がおかしくなったり、目盛が逆になったりして、1か月ぐらいはまっていた。そこで、matplotlib.specgramの中身を確認すると、imshow()を使っていることが分かった。前処理を含み参考にしてgwtspecgramを実装する。

→matplotlib.specgram

noimg
around,right

タイトル title()

サンプルコードを見ていると、titleの表示方法が2種類見られる。

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('axes title')
fig = plt.figure()
ax = fig.gca()
plt.title('axes title')

違いを調べるために、plt.title()の中身を確認したところ、中では同じset_title()が呼ばれていた。matlab風にするためのラッピングかもしれない。

def title(s, *args, **kwargs):
   l =  gca().set_title(s, *args, **kwargs)
   draw_if_interactive()
   return l

Matplotlib イベントハンドラ

Matplotlibでは、マウスクリックやドラッグ、キーボード操作に対するハンドラが実装されている。PySidePyQt?のようなシグナル・スロットのようにconnectを使って、イベントを捕まえることができる。

→Event handling and picking

イベントの接続 (mpl_connect)

# --
import matplotlib.pyplot as plt
import numpy as np
# --
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))
# --
def onclick(event):
   # Eventの基本プロパティ (matplotlib.backend_bases.Event)
   print event.name      # イベント名
   print event.canvas   # FigureCanvasインスタンス
   print evnet.guiEvent # トリガーされたGUIイベント
   # MouseEventのプロパティ
   print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
       event.button, event.x, event.y, event.xdata, event.ydata)
# --
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS