- 追加された行はこの色です。
- 削除された行はこの色です。
- [[→axis_limit_selecter.py>https://gist.github.com/peace098beat/87aa1b98d611ba88d8ab]]
-- figureの横に小さなヒストグラムを表示し、グラフのlim()を設定するウィジェット
#ref(axis_limit_selector.jpg,,50%)
** ドキュメント [#o3ab97a0]
[[→継承関係図>https://fossies.org/dox/matplotlib-1.4.3/classmatplotlib_1_1contour_1_1QuadContourSet.html]]
[[→公式リファレンス>http://turbare.net/transl/scipy-lecture-notes/intro/matplotlib/matplotlib.html]]
[[→docs>http://matplotlib.org/contents.html]]
[[→User's Guide>http://matplotlib.org/users/index.html]]
[[→Beginner’s Guide>http://matplotlib.org/users/beginner.html]]
[[→Advanced Guide>http://matplotlib.org/users/developer.html]]
** モジュールのインポート [#sce15176]
Matplotibを使ってグラフ描画するスクリプトは、PySideへそのまま移植したいと思っているので、pylabは使わず、pltとnpを使っていく.
import matplotlib.pyplot as plt
import numpy as np
** webアプリケーションとしてグラフを保存する [#d73228cb]
多くの初心者は、Matplotlibをwebアプリケーションサーバで利用するときにエラーが出て困っている。なぜなら、MatplotlibはGUIで使う事を前提としており、X11への接続が必要になるからである。しかし、Webサーバーでも簡単なおまじないで使う事はできる。matplotlib.pyplotを呼び出す前にmatplotlib.use('Agg')を宣言するのだ。これで、matplolibはバックエンドでのみ動作し、GUIを必要とせずグラフを描画する事ができる。
[[→How-To-Matplotlib-Figure>http://matplotlib.org/faq/howto_faq.html#plotting-howto]]
# 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 handler[#jb102e49]
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)
** figure [#g2be3270]
[[→matplotlib.figure>http://matplotlib.org/api/figure_api.html]]
[[→1.4.3.1 Figuresの使い方>http://turbare.net/transl/scipy-lecture-notes/intro/matplotlib/matplotlib.html#figures]]
fig = plt.figure(figsize=(1,5), dpi=72, facecolor=[0,0,0], edgecolor=None, linewidth=0.0)
class matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None)
fig = plt.figure(figsize=(10,2), dpi=72, facecolor=[1,1,1], edgecolor=[0,0,0], linewidth=1.0, frameon=False, tight_layout=False)
num: figureの数
figsize: figureのサイズ(width, height)単位はインチ
dpi: ドット/インチ
facecolor: 描画背景色
edgecolor: 縁の色
frameon: (bool) figureのフレームを描画するかどうか
** axes [#m9552554]
[[→matplotlib.pyplot.axis()>http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.axis]]
ax = gca()
[xmin, xmax, ymin, ymax] = ax.axis()
ax.axis([xmin, xmax, ymin, ymax])
ax.axis('off')
ax.axis('scaled')
ax.axis('tight')
ax.axis('image')
ax.axis('auto')
ax.axis('normal')
** grid [#u605ac4d]
ax.grid()
** fiugre, axes handles[#f171971a]
plt.close('all')
fig, ax = plt.subplots()
[[→Artist>http://matplotlib.org/1.3.0/users/artists.html]]
** subplots [#kf4bf407]
[[→subplots_demo.py>http://matplotlib.org/examples/pylab_examples/subplots_demo.html#pylab-examples-example-code-subplots-demo-py]]
[[→subplotsの使い方(ipython)>https://gist.github.com/peace098beat/649a58647993d96158a6]]
f, axarr = plt.subplots(2,2)
axarr[0, 0].plot(x, y)
** subplot2grid [#de3afb13]
plt.subplot2grid( (5,5), (0,0), colspan=3)
plt.subplot2grid( (5,5), (0,3), colspan=2)
plt.subplot2grid( (5,5), (1,4))
plt.subplot2grid( (5,5), (1,0), colspan=4)
plt.subplot2grid( (5,5), (2,0), colspan=5, rowspan=3)
** オブジェクト [#n9ff3de1]
#ref(Refference-matplotlib.pyplot.py)
- [[matplotlib.axes.axes>http://matplotlib.org/api/axes_api.html]]
- [[matplotlib.lines>http://matplotlib.org/api/lines_api.html#module-matplotlib.lines]]
- matplotlib.lines
-- class matplotlib.lines.Line2D(xdata, ydata,...)
-- class matplotlib.lines.VertexSelector(line)
-- matplotlib.lines.segment_hits(cx, cy, x, y, radius)
** fig.tight_layout() [#o2c92f56]
subplotの中身について、tickables, axis, labels, titlesの大きさを、タイトなレイアウトにしてくれる
[[→Tight Layout guide>http://matplotlib.org/1.4.1/users/tight_layout_guide.html]]
#ref(s-tight_layout0.jpg)
#ref(s-tight_layout1.jpg)
** Contour [#p5c671a5]
[[pyplot.contour>http://matplotlib.org/devdocs/api/pyplot_api.html#matplotlib.pyplot.contourf]]
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 [#ebd62f48]
[[pyplot.Colormap>http://matplotlib.org/devdocs/api/colors_api.html#matplotlib.colors.Colormap]]
#ref(mpl_cmap.png,,20%)
[[→ Documenting the matplotlib colormaps>https://gist.github.com/endolith/2719900]]
** matplotlib.specgram [#l60e827c]
ガボールウェーブレットの結果をスペクトログラムの様に表示したいが、imshow()だと、縦横比がおかしくなったり、目盛が逆になったりして、1か月ぐらいはまっていた。そこで、matplotlib.specgramの中身を確認すると、imshow()を使っていることが分かった。前処理を含み参考にしてgwtspecgramを実装する。
[[→matplotlib.specgram>https://gist.github.com/peace098beat/9812bd04612a3f656abc]]
#ref(figure_specgram.png,,noimg,30%)
#ref(figure_scarogram.png,,around,right,30%)
** タイトル title() [#b1ceeae7]
サンプルコードを見ていると、titleの表示方法が2種類見られる。
- Basic text commands
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風にするためのラッピングかもしれない。
- plt.title()
def title(s, *args, **kwargs):
l = gca().set_title(s, *args, **kwargs)
draw_if_interactive()
return l
** 軸ラベル [#c7cdacd0]
plt.plot( [3,1,4,1,5,9,2,6,5], label = "Data 1")
plt.plot( [3,5,8,9,7,9,3,2,3], label = "Data 2")
plt.legend() # 凡例を表示
plt.title("Graph Title")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
* Matplotlib イベントハンドラ [#h9f7fc01]
Matplotlibでは、マウスクリックやドラッグ、キーボード操作に対するハンドラが実装されている。PySideやPyQtのようなシグナル・スロットのようにconnectを使って、イベントを捕まえることができる。
[[→Event handling and picking>http://matplotlib.org/users/event_handling.html]]
** イベントの接続 (mpl_connect) [#w57087dd]
# --
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()
** イベントハンドラでfigure,axesの呼び出し [#a939a3c2]
line, = plt.plot(X)
line.figure
line.figure.canvas
line.figure.canvas.draw()
line.set_x(x1)
line.set_y(y1)
line.get_xdata()
line.get_ydata()
line.axes
** [[Event handling and picking>http://matplotlib.org/users/event_handling.html#event-handling-and-picking]] [#j5dc95fb]
- [[Event name Class and description>http://matplotlib.org/users/event_handling.html#event-connections]]
-- ‘button_press_event’ MouseEvent - mouse button is pressed
-- ‘button_release_event’ MouseEvent - mouse button is released
-- ‘draw_event’ DrawEvent - canvas draw
-- ‘key_press_event’ KeyEvent - key is pressed
-- ‘key_release_event’ KeyEvent - key is released
-- ‘motion_notify_event’ MouseEvent - mouse motion
-- ‘pick_event’ PickEvent - an object in the canvas is selected
-- ‘resize_event’ ResizeEvent - figure canvas is resized
-- ‘scroll_event’ MouseEvent - mouse scroll wheel is rolled
-- ‘figure_enter_event’ LocationEvent - mouse enters a new figure
-- ‘figure_leave_event’ LocationEvent - mouse leaves a figure
-- ‘axes_enter_event’ LocationEvent - mouse enters a new axes
-- ‘axes_leave_event’ LocationEvent - mouse leaves an axes
*** [[Event bases>http://matplotlib.org/users/event_handling.html#event-attributes]] [#p1042009]
event.name
event.canvas
event.guiEvent
*** [[Mouse Event>http://matplotlib.org/users/event_handling.html#draggable-rectangle-exercise]] [#pcc28e3c]
event.x
event.y
event.xdata
event.ydata
event.inaxes
*** [[pick event>http://matplotlib.org/users/event_handling.html#simple-picking-example]] [#qcb313b5]
event.artist
event.ind
line = event.artist
xdata = line.get_xdata()
ydata = line.get_ydata()
ind = event.ind
x0 = xdata[ind]
y0 = ydata[ind]
* 軸の設定 [#f88d8f7f]
** xlim, ylim [#h3f78fde]
カレントのaxesの最大値と最小値を取得する
[[→matplotlib.pyplot.xlim()>http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.xlim]]
xmin, xmax = plt.xlim() # return the current xlim
plt.xlim( (xmin, xmax) ) # set the xlim to xmin, xmax
plt.xlim( xmin, xmax ) # set the xlim to xmin, xmax
しかしこれだと、PySideでは使いづらい。中身をみると結局はgca()を使ってcurrentなaxesを取得してaxesのメソッドを呼び出している。
[[→matplotlib.axes.get_xlim()>http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.get_xlim]]
fig, ax = plt.subplot(111)
xmin, xmax = ax.get_xlim()
ax.set_xlim( xmin, xmax )
** 目盛の設定 [#w3d7f234]
# 目盛を消す
ax2.set_xticklabels([])
ax2.set_yticklabels([])
plt.locator_params(nbins=25, axis='x', tight=True)
plt.locator_params(nbins=10, axis='y', tight=True)
* clim [#sf0b7f93]
[[→Image tutoriall>http://matplotlib.org/users/image_tutorial.html#examining-a-specific-data-range]]
定義は以下
AxisImage.set_clim()
通常のaxesにはset_climは存在しない。axesハンドルからAxisImageオブジェクトを取得するには
# for im in ax1.get_images():
# ax1.set_clim(ax2.get_ylim())
im.set_clim(ax2.get_ylim())
imgplot = plt.imshow(img)
imgplot.set_clim(0, 0.7)
** contourfの場合 [#a9caa6a6]
cf = contourf(X,Y,Z)
cmin, cmax = c.get_clim()
** Matplotlib Style Sheet (スタイルシート) [#q1f51f5b]
- [[A sample matplotlibrc file>http://matplotlib.org/1.3.1/users/customizing.html]]
** ピーク検出 [#i2c6bc3a]
''' ピークをプロット Scipyでピーク検出 '''
from scipy import signal
# 極大値検索
maxId = signal.argrelmax(Pdata_ave, order=10, mode='wrap')
maxId = maxId[0][:]
self.axes.hold(True)
self.axes.plot(self.plot_frange[maxId], Pdata_ave[maxId], 'ro')
self.axes.hold(False)
for id in maxId:
s = '%0.1f' % (self.plot_frange[id])
self.axes.annotate(s, xy=(self.plot_frange[id], Pdata_ave[id]), fontsize=10,
horizontalalignment='center', verticalalignment='bottom')
** GWTグラフのTips [#p0566f52]
# def imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None,
# vmin=None, vmax=None, origin=None, extent=None, shape=None,
# filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None,
# hold=None, **kwargs):
#
#ref(figure_1.png,,30%)
なぜかわからないが、そのまま使うと外側に空白ができる。
gdata = 20*np.log10(gwt.T)
extent = t[0], t[-1], f[0], f[-1]
plt.imshow(gdata, cmap='jet', extent=extent, origin='lower', interpolation='nearest')
plt.axis('auto')
#ref(figure_2.png,,30%)
axis('tight')を使うことで綺麗に表示された。
gdata = 20*np.log10(gwt.T)
extent = t[0], t[-1], f[0], f[-1]
plt.imshow(gdata, cmap='jet', extent=extent, origin='lower', interpolation='nearest')
plt.axis('tight')