2016-09-28 4 views
2

私は、有効なポイントをクリックしたときにmatplotlibインタラクティブでプロットされたOHLCグラフを作ろうとしています。データはフォームのパンダのデータフレームとして格納されmatplotlibでpythonの燭台のグラフをクリックできるようにするには

index  PX_BID PX_ASK PX_LAST PX_OPEN PX_HIGH PX_LOW 
2016-07-01 1.1136 1.1137 1.1136 1.1106 1.1169 1.1072 
2016-07-04 1.1154 1.1155 1.1154 1.1143 1.1160 1.1098 
2016-07-05 1.1076 1.1077 1.1076 1.1154 1.1186 1.1062 
2016-07-06 1.1100 1.1101 1.1100 1.1076 1.1112 1.1029 
2016-07-07 1.1062 1.1063 1.1063 1.1100 1.1107 1.1053 

私はmatplotlibののローソク足の機能とそれをプロットしています:

https://pythonprogramming.net/static/images/matplotlib/candlestick-ohlc-graphs-matplotlib-tutorial.png

candlestick2_ohlc(ax1, df['PX_OPEN'],df['PX_HIGH'],df['PX_LOW'],df['PX_LAST'],width=1) 

、それはこのように気にいらに見えるプロットすると

私は、クリックしたポイントの値、日付、およびオープン、ハイロー、クローズのいずれかをコンソールに出力します。これまでのところ、私は次のようなものを持っています:

fig, ax1 = plt.subplots() 

ax1.set_title('click on points', picker=True) 
ax1.set_ylabel('ylabel', picker=True, bbox=dict(facecolor='red')) 
line = candlestick2_ohlc(ax1, df['PX_OPEN'],df['PX_HIGH'],df['PX_LOW'],df['PX_LAST'],width=0.4) 

def onpick1(event): 
    if isinstance(event.artist, (lineCollection, barCollection)): 
     thisline = event.artist 
     xdata = thisline.get_xdata() 
     ydata = thisline.get_ydata() 
     ind = event.ind 
     #points = tuple(zip(xdata[ind], ydata[ind])) 
     #print('onpick points:', points) 
     print('X='+str(np.take(xdata, ind)[0])) # Print X point 
     print('Y='+str(np.take(ydata, ind)[0])) # Print Y point 

fig.canvas.mpl_connect('pick_event', onpick1) 
plt.show() 

このコードでは、ランとポイントをクリックすると何も印刷されません。私はインタラクティブmatplotlibのグラフの例を見ると、彼らのようなプロット機能で引数を持っている傾向がある:

line, = ax.plot(rand(100), 'o', picker=5) 

しかし、candlestick2_ohlcは「ピッカー」引数を取りません。どのように私はこれを回避するためのヒント?あなたは(http://matplotlib.org/api/artist_api.html#matplotlib.artist.Artist.set_pickerを参照)ピックイベントを有効にするか、またはフロートなどの点で許容範囲を与えるためにset_picker(True)を設定する必要が

おかげ

答えて

1

あなたのケースでは、ax1.set_picker(True)は、mouseeventがax1を超えるたびにイベントを発生させたい場合に使用します。

キャンドルチャートの要素でピックイベントを有効にすることができます。私はドキュメントを読んで、candlestick2_ohlcは2つのオブジェクトのタプルを返します:LineCollectionPolyCollectionです。ですから、これらのオブジェクトに名前を付け、それらにtrueに

(lines,polys) = candlestick2_ohlc(ax1, ...) 
lines.set_picker(True) # collection of lines in the candlestick chart 
polys.set_picker(True) # collection of polygons in the candlestick chart 

をピッカーを設定できるイベントind = event.ind[0]のインデックスは、マウスイベントが含まれてコレクション内のどの要素を教えてくれます(event.indマウスイベント以来、インデックスのリストを返します。複数の項目に関係する可能性があります)。

燭台でピックイベントをトリガーすると、元のデータフレームからデータを印刷できます。

ここではいくつかの作業コードが

import matplotlib.pyplot as plt 
from matplotlib.collections import LineCollection, PolyCollection 
from matplotlib.text import Text 
from matplotlib.finance import candlestick2_ohlc 
import numpy as np 
import pandas as pd 

np.random.seed(0) 
dates = pd.date_range('20160101',periods=7) 
df = pd.DataFrame(np.reshape(1+np.random.random_sample(42)*0.1,(7,6)),index=dates,columns=["PX_BID","PX_ASK","PX_LAST","PX_OPEN","PX_HIGH","PX_LOW"]) 
df['PX_HIGH']+=.1 
df['PX_LOW']-=.1 

fig, ax1 = plt.subplots() 

ax1.set_title('click on points', picker=20) 
ax1.set_ylabel('ylabel', picker=20, bbox=dict(facecolor='red')) 

(lines,polys) = candlestick2_ohlc(ax1, df['PX_OPEN'],df['PX_HIGH'],df['PX_LOW'],df['PX_LAST'],width=0.4) 
lines.set_picker(True) 
polys.set_picker(True) 

def onpick1(event): 
    if isinstance(event.artist, (Text)): 
     text = event.artist 
     print 'You clicked on the title ("%s")' % text.get_text() 
    elif isinstance(event.artist, (LineCollection, PolyCollection)): 
     thisline = event.artist 
     mouseevent = event.mouseevent 
     ind = event.ind[0] 
     print 'You clicked on item %d' % ind 
     print 'Day: ' + df.index[ind].normalize().to_datetime().strftime('%Y-%m-%d') 
     for p in ['PX_OPEN','PX_OPEN','PX_HIGH','PX_LOW']: 
      print p + ':' + str(df[p][ind])  
     print('x=%d, y=%d, xdata=%f, ydata=%f' % 
      (mouseevent.x, mouseevent.y, mouseevent.xdata, mouseevent.ydata)) 



fig.canvas.mpl_connect('pick_event', onpick1) 
plt.show() 
+0

だおかげで、しかし、これはエラーにつながる: はAttributeError: 'AxesSubplot' オブジェクトが無属性 'get_xdata' 任意のアイデアを持っていますか? –

関連する問題