FrontPage / Python / Matplotlib

http://personals-index.com/index1552.html http://personals-index.com/index1553.html http://personals-index.com/index1554.html http://personals-index.com/index1555.html http://personals-index.com/index1556.html http://personals-index.com/index1557.html http://personals-index.com/index1558.html http://personals-index.com/index1559.html http://personals-index.com/index1560.html http://personals-index.com/index1561.html http://personals-index.com/index1562.html http://personals-index.com/index1563.html http://personals-index.com/index1564.html http://personals-index.com/index1565.html http://personals-index.com/index1566.html http://personals-index.com/index1567.html http://personals-index.com/index1568.html http://personals-index.com/index1569.html http://personals-index.com/index1570.html http://personals-index.com/index1571.html http://personals-index.com/index1572.html http://personals-index.com/index1573.html http://personals-index.com/index1574.html http://personals-index.com/index1575.html http://personals-index.com/index1576.html http://personals-index.com/index1577.html http://personals-index.com/index1578.html http://personals-index.com/index1579.html http://personals-index.com/index1580.html http://personals-index.com/index1581.html http://personals-index.com/index1582.html http://personals-index.com/index1583.html http://personals-index.com/index1584.html http://personals-index.com/index1585.html http://personals-index.com/index1586.html http://personals-index.com/index1587.html http://personals-index.com/index1588.html http://personals-index.com/index1589.html http://personals-index.com/index1590.html http://personals-index.com/index1591.html http://personals-index.com/index1592.html http://personals-index.com/index1593.html http://personals-index.com/index1594.html http://personals-index.com/index1595.html http://personals-index.com/index1596.html http://personals-index.com/index1597.html http://personals-index.com/index1598.html http://personals-index.com/index1599.html http://personals-index.com/index1500.html http://personals-index.com/index1501.html http://personals-index.com/index1502.html http://personals-index.com/index1503.html http://personals-index.com/index1504.html http://personals-index.com/index1505.html http://personals-index.com/index1506.html http://personals-index.com/index1507.html http://personals-index.com/index1508.html http://personals-index.com/index1509.html http://personals-index.com/index1510.html http://personals-index.com/index1511.html http://personals-index.com/index1512.html http://personals-index.com/index1513.html http://personals-index.com/index1514.html http://personals-index.com/index1515.html http://personals-index.com/index1516.html http://personals-index.com/index1517.html http://personals-index.com/index1518.html http://personals-index.com/index1518.html http://personals-index.com/index1518.html http://personals-index.com/index1521.html http://personals-index.com/index1522.html http://personals-index.com/index1523.html http://personals-index.com/index1524.html http://personals-index.com/index1525.html http://personals-index.com/index1526.html http://personals-index.com/index1527.html http://personals-index.com/index1528.html http://personals-index.com/index1529.html http://personals-index.com/index1530.html http://personals-index.com/index1531.html http://personals-index.com/index1532.html http://personals-index.com/index1533.html http://personals-index.com/index1534.html http://personals-index.com/index1535.html http://personals-index.com/index1536.html http://personals-index.com/index1537.html http://personals-index.com/index1538.html http://personals-index.com/index1539.html http://personals-index.com/index1540.html http://personals-index.com/index1541.html http://personals-index.com/index1542.html http://personals-index.com/index1543.html http://personals-index.com/index1544.html http://personals-index.com/index1545.html http://personals-index.com/index1546.html http://personals-index.com/index1547.html http://personals-index.com/index1548.html http://personals-index.com/index1549.html http://personals-index.com/index1552.html http://personals-index.com/index1551.html http://personals-index.com/index1550.html http://personals-index.com/index1652.html http://personals-index.com/index1653.html http://personals-index.com/index1654.html http://personals-index.com/index1655.html http://personals-index.com/index1656.html http://personals-index.com/index1657.html http://personals-index.com/index1658.html http://personals-index.com/index1659.html http://personals-index.com/index1660.html http://personals-index.com/index1661.html http://personals-index.com/index1662.html http://personals-index.com/index1663.html http://personals-index.com/index1664.html http://personals-index.com/index1665.html http://personals-index.com/index1666.html http://personals-index.com/index1667.html http://personals-index.com/index1668.html http://personals-index.com/index1669.html http://personals-index.com/index1670.html http://personals-index.com/index1671.html http://personals-index.com/index1672.html http://personals-index.com/index1673.html http://personals-index.com/index1674.html http://personals-index.com/index1675.html http://personals-index.com/index1676.html http://personals-index.com/index1677.html http://personals-index.com/index1678.html http://personals-index.com/index1679.html http://personals-index.com/index1680.html http://personals-index.com/index1681.html http://personals-index.com/index1682.html http://personals-index.com/index1683.html http://personals-index.com/index1684.html http://personals-index.com/index1685.html http://personals-index.com/index1686.html http://personals-index.com/index1687.html http://personals-index.com/index1688.html http://personals-index.com/index1689.html http://personals-index.com/index1690.html http://personals-index.com/index1691.html http://personals-index.com/index1692.html http://personals-index.com/index1693.html http://personals-index.com/index1694.html http://personals-index.com/index1695.html http://personals-index.com/index1696.html http://personals-index.com/index1697.html http://personals-index.com/index1698.html

スタイルの変更

plt.style.use('dark_background')
plt.style.use('ggplot')

subplot同士で軸の共有

 fig = plt.figure()
 ax1 = fig.add_subplot(121)
 ax2 = fig.add_subplot(122, sharey=ax1)

plotのラインカラー

plt.plot(frange_khz, 20 * np.log10(data), c='gray', linewidth=0.5)
  • figureの横に小さなヒストグラムを表示し、グラフのlim()を設定するウィジェット
axis_limit_selector.jpg

ドキュメント

→継承関係図

→公式リファレンス

→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 handler

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

→matplotlib.figure

→1.4.3.1 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

→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

ax.grid()

fiugre, axes handles

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

→Artist

subplots

→subplots_demo.py

→subplotsの使い方(ipython)

f, axarr = plt.subplots(2,2)
axarr[0, 0].plot(x, y)

subplot2grid

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)

オブジェクト

  • 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()

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種類見られる。

  • 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

軸ラベル

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 イベントハンドラ

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()

イベントハンドラでfigure,axesの呼び出し

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

  • Event name Class and description
    • ‘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

event.name
event.canvas
event.guiEvent

Mouse Event

event.x
event.y
event.xdata
event.ydata
event.inaxes

pick event

event.artist
event.ind
line = event.artist
xdata = line.get_xdata()
ydata = line.get_ydata()
ind = event.ind
x0 = xdata[ind]
y0 = ydata[ind]

軸の設定

xlim, ylim

カレントのaxesの最大値と最小値を取得する

→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()

fig, ax = plt.subplot(111)
xmin, xmax = ax.get_xlim()
ax.set_xlim( xmin, xmax )

目盛の設定

# 目盛を消す
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

→Image tutoriall

定義は以下

 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の場合

cf = contourf(X,Y,Z)
cmin, cmax = c.get_clim()

Matplotlib Style Sheet (スタイルシート)

ピーク検出

       ''' ピークをプロット 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

   # 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):
   #
figure_1.png

なぜかわからないが、そのまま使うと外側に空白ができる。

   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')
figure_2.png

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')
トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
添付ファイル: filefigure_2.png 838件 [詳細] filefigure_1.png 891件 [詳細] fileaxis_limit_selector.jpg 786件 [詳細] fileRefference-matplotlib.pyplot.py 990件 [詳細] files-tight_layout1.jpg 705件 [詳細] files-tight_layout0.jpg 815件 [詳細] filefigure_specgram.png 836件 [詳細] filefigure_scarogram.png 927件 [詳細] filempl_cmap.png 1095件 [詳細]
Last-modified: 2016-12-07 (水) 16:28:21 (2690d)