[英]How to matplotlib blit artist outside axes?
https://matplotlib.org/stable/gallery/event_handling/cursor_demo.html
我試圖在右軸上制作一個帶有注釋的十字線光標來顯示 Y 值
一切正常,除非藝術家/注釋繪制在軸外
繼續繪制圖形會起作用,但我的圖表有很多數據,每次繪制會導致 0.5 - 0.7 秒,這對於游標函數 self.ax.figure.canvas.draw() 來說非常滯后
我的猜測是當我保存背景時,“self.ax.bbox”只是為軸內的東西保存圖像,這就是為什么當它 blit 它在軸外不起作用? self.background = self.ax.figure.canvas.copy_from_bbox(self.ax.bbox)
我有很多嘗試,但沒有運氣......需要一些建議
下面是一個簡單的例子(我的情節將是一個沉重的情節,我無法在 mousemove 事件上繼續調用 draw() )我試圖制作一個平滑的十字線光標,並在右軸上進行注釋
import matplotlib.pyplot as plt
import numpy as np
class BlittedCursor:
"""
A cross hair cursor using blitting for faster redraw.
"""
def __init__(self, ax):
self.ax = ax
self.background = None
self.horizontal_line = ax.axhline(color='k', lw=0.8, ls='--')
self.vertical_line = ax.axvline(color='k', lw=0.8, ls='--')
# text location in axes coordinates
self.text = ax.text(0.95, 0, '', transform=ax.get_yaxis_transform())
self._creating_background = False
ax.figure.canvas.mpl_connect('draw_event', self.on_draw)
def on_draw(self, event):
self.create_new_background()
def set_cross_hair_visible(self, visible):
need_redraw = self.horizontal_line.get_visible() != visible
self.horizontal_line.set_visible(visible)
self.vertical_line.set_visible(visible)
self.text.set_visible(visible)
return need_redraw
def create_new_background(self):
if self._creating_background:
# discard calls triggered from within this function
return
self._creating_background = True
self.set_cross_hair_visible(False)
self.ax.figure.canvas.draw()
self.background = self.ax.figure.canvas.copy_from_bbox(self.ax.bbox)
self.set_cross_hair_visible(True)
self._creating_background = False
def on_mouse_move(self, event):
if self.background is None:
self.create_new_background()
if not event.inaxes:
need_redraw = self.set_cross_hair_visible(False)
if need_redraw:
self.ax.figure.canvas.restore_region(self.background)
self.ax.figure.canvas.blit(self.ax.bbox)
else:
self.set_cross_hair_visible(True)
# update the line positions
x, y = event.xdata, event.ydata
self.horizontal_line.set_ydata(y)
self.vertical_line.set_xdata(x)
self.text.set_text('y=%1.2f' % (y))
self.text.set_y(y)
self.ax.figure.canvas.restore_region(self.background)
self.ax.draw_artist(self.horizontal_line)
self.ax.draw_artist(self.vertical_line)
self.ax.draw_artist(self.text)
self.ax.figure.canvas.blit(self.ax.bbox)
x = np.arange(0, 1, 0.01)
y = np.sin(2 * 2 * np.pi * x)
fig, ax = plt.subplots()
ax.set_title('Blitted cursor')
ax.plot(x, y, 'o')
blitted_cursor = BlittedCursor(ax)
fig.canvas.mpl_connect('motion_notify_event', blitted_cursor.on_mouse_move)
plt.show()
我實際上通過下面的更改解決了問題......但我還是不明白。 任何人都可以進一步解釋嗎? 我的猜測是ax.get_figure()
也會獲取軸外的圖像嗎? 和ax.clipbox
意味着整個數字?
self.background = self.ax.figure.canvas.copy_from_bbox(self.ax.get_figure().bbox)
self.ax.figure.canvas.blit(self.ax.clipbox)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.