2012年6月30日土曜日

matplotlib その3(プロットした点をクリック、ハイライトする)


matplotlibでマウスのイベントを取得して、クリックした点のデータをとってくる。
参考URLを勉強がてら少しシンプルにしてみる。
描画データをPointBrowserに関連付けておいて、データをクリックするたびに、その上に黄色い薄い丸を描画するようにしている。


メモ:
plotのpicker=5でクリックしたときの許容範囲を決定。
複数のデータがクリック範囲に入ったときも、そのうち1番最初の1つのみを使う。(ind[0])
mpl_connectを使えば、マウス以外にもイベントを取得できる。ハンドラーというのだろう。(http://matplotlib.sourceforge.net/api/backend_bases_api.html#matplotlib.backend_bases.FigureCanvasBase.mpl_connect)


参考URL:http://matplotlib.sourceforge.net/examples/event_handling/data_browser.html

from numpy.random import rand
from pylab import figure, show


class PointBrowser:
    """
    pass a subplot to __init__
    overwrite the yellow circle on the clicked data
    """
    def __init__(self, fig, ax):
        self.fig = fig
        self.text = ax.text(0.05, 0.95, 'selected: none',
                            transform=ax.transAxes, va='top')


        self.selected,  = ax.plot([], [], 'o', ms=12, alpha=0.4,
                                  color='yellow', visible=False)

    def onpick(self, event):
        """
        it picks up the index of clicked data

        """
        if not len(event.ind):
            return True

        ind = event.ind[0]
        x = event.artist.get_xdata()[ind]
        y = event.artist.get_ydata()[ind]
        clicked = (x, y)

        self.selected.set_visible(True)
        self.selected.set_data(clicked)
        self.text.set_text(' x: %f\n y: %f'%(clicked))
        self.fig.canvas.draw()

if __name__ == "__main__":
    xs = rand(100)
    ys = rand(100)

    fig = figure()
    ax = fig.add_subplot(111)
    ax.set_title('picking demo')
    ax.plot(xs, ys, 'o', picker=5)  # 5 points tolerance

    browser = PointBrowser(fig, ax)
    fig.canvas.mpl_connect('pick_event', browser.onpick)

    show()




matplotlib 軸の目盛り設定

軸の目盛りは自動で最大値をつけてくれるけど、
手動で付けたい時はset_yticks(list)を使う。

def main():
    fig = figure()
    ax1 = fig.add_subplot(111)
    ax1.plot(rand(10))
    ax1.set_yticks(np.arange(0, 1.1, 0.1))

    show()

if __name__ == "__main__":
    main()







matplotlib その2 (複数のプロット)

matplotlib で複数のグラフを表示する。

1つのウィンドウに2つのグラフを表示する場合
from matplotlib.pyplot import figure, show
import numpy as np
from numpy.random import rand

def main():
    fig = figure()
    ax1 = fig.add_subplot(211)
    ax1.plot(rand(10))
    ax1.set_yticks(np.arange(0, 1.1, 0.1))

    ax2 = fig.add_subplot(212)
    ax2.plot(rand(10), 'o')
    show()

if __name__ == "__main__":
    main()


2つのウィンドウにそれぞれプロットするときは
    fig = figure()

    ax1 = fig.add_subplot(111)
    ax1.plot(rand(10))
    ax1.set_yticks(np.arange(0, 1.1, 0.1))

    fig = figure()
    ax2 = fig.add_subplot(111)
    ax2.plot(rand(10), 'o')
    show()





fig2としなくても描画はできるようだ。
試しにfig=figure()を2回読んだときのfigの中身を調べてみたら
numberとかいうのがあって、それが2になっていた。
以下参考までに
>>> fig = figure()
>>> fig = figure()
>>> fig.__dict__
{'_agg_filter': None,
 '_alpha': None,
 '_animated': False,
 '_axobservers': [],
 '_axstack': ,
 '_cachedRenderer': None,
 '_clipon': True,
 '_clippath': None,
 '_contains': None,
 '_dpi': 80,
 '_gid': None,
 '_hold': True,
 '_label': '',
 '_lod': False,
 '_oid': 0,
 '_picker': None,
 '_propobservers': {},
 '_rasterized': None,
 '_remove_method': None,
 '_snap': None,
 '_transform': None,
 '_transformSet': False,
 '_url': None,
 '_visible': True,
 'artists': [],
 'bbox': TransformedBbox(Bbox(array([[ 0.,  0.],
       [ 8.,  6.]])), Affine2D(array([[ 80.,   0.,   0.],
       [  0.,  80.,   0.],
       [  0.,   0.,   1.]]))),
 'bbox_inches': Bbox(array([[ 0.,  0.],
       [ 8.,  6.]])),
 'callbacks': ,
 'canvas': ,
 'clipbox': None,
 'dpi_scale_trans': Affine2D(array([[ 80.,   0.,   0.],
       [  0.,  80.,   0.],
       [  0.,   0.,   1.]])),
 'eventson': False,
 'figure': None,
 'figurePatch': ,
 'frameon': True,
 'images': [],
 'legends': [],
 'lines': [],
 'number': 2,
 'patch': ,
 'patches': [],
 'show':  at 0x03A35730>,
 'subplotpars': ,
 'suppressComposite': None,
 'texts': [],
 'transFigure': BboxTransformTo(TransformedBbox(Bbox(array([[ 0.,  0.],
       [ 8.,  6.]])), Affine2D(array([[ 80.,   0.,   0.],
       [  0.,  80.,   0.],
       [  0.,   0.,   1.]])))),
 'x_isdata': True,
 'y_isdata': True}