鼠标悬停在pyp的matplotlib烛台中

时间:2012-08-02 14:15:02

标签: python events matplotlib finance

我已经实现了这个例子:

http://matplotlib.sourceforge.net/examples/pylab_examples/finance_demo.html?highlight=candlestick

我想为烛台实现鼠标悬停功能,这样我就可以在某个面板的弹出窗口或标签中看到烛台的打开/高/低/关闭。我跟随着:

http://matplotlib.sourceforge.net/examples/event_handling/pick_event_demo.html

不幸的是,功能:

candlestick(ax, quotes, width=0.6)

没有picker=True个关键字。还有其他方法可以实现鼠标悬停功能吗?

matplotlib.finance的文档 http://doc.astro-wise.org/matplotlib.finance.html

2 个答案:

答案 0 :(得分:2)

我已经提供了一些链接到一些有价值信息的答案。既然你想通过查看数据而不是轴上的艺术家来处理事物,我想我会给你一些帮助。我所做的是采用matplotlib烛台示例,并添加一个鼠标移动事件,它打印鼠标当前所在的日期,以及3个最近(时间)的股票。从这一点来看,它应该只是将两个答案结合起来产生预期结果:

#!/usr/bin/env python
import matplotlib.pyplot as plt
import pylab
from matplotlib.dates import  DateFormatter, WeekdayLocator, HourLocator, \
     DayLocator, MONDAY, num2date
from matplotlib.finance import quotes_historical_yahoo, candlestick,\
     plot_day_summary, candlestick2

# (Year, month, day) tuples suffice as aregs for quotes_historical_yahoo
date1 = ( 2004, 2, 1)
date2 = ( 2004, 4, 12 )


mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
alldays    = DayLocator()              # minor ticks on the days
weekFormatter = DateFormatter('%b %d')  # Eg, Jan 12
dayFormatter = DateFormatter('%d')      # Eg, 12

quotes = quotes_historical_yahoo('INTC', date1, date2)
if len(quotes) == 0:
    raise SystemExit

fig = plt.figure()
fig.subplots_adjust(bottom=0.2)
ax = fig.add_subplot(111)
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)

candlestick(ax, quotes, width=0.6)

ax.xaxis_date()
ax.autoscale_view()
plt.setp(ax.get_xticklabels(), rotation=45, horizontalalignment='right')


def on_move(event):
    ax = event.inaxes
    if ax is not None:
        # convert x y device coordinates to axes data coordinates
        date_ordinal, y = ax.transData.inverted().transform([event.x, event.y])

        # convert the numeric date into a datetime
        date = num2date(date_ordinal)

        # sort the quotes by their distance (in time) from the mouse position
        def sorter(quote):
            return abs(quote[0] - date_ordinal)
        quotes.sort(key=sorter)

        print 'on date %s the nearest 3 openings were %s at %s respectively' % \
                        (date, 
                         ', '.join([str(quote[1]) for quote in quotes[:3]]),
                         ', '.join([str(num2date(quote[0])) for quote in quotes[:3]]))


on_move_id = fig.canvas.mpl_connect('motion_notify_event', on_move)


plt.show()

HTH

答案 1 :(得分:0)

我写了一个答案来处理“鼠标悬停”事件here。这将是一个很好的第一点,可以找出如何做类似的事情。