我有一个带有多个轴的 matplotlib 图形,并且滚动/缩放变得非常慢。有什么办法可以加快速度吗?
作为示例,尝试滚动使用以下代码生成的轴之一:
import matplotlib.pyplot as plt
fig,plts = plt.subplots(10,10)
plt.show()
(我在 Mac 上,使用 macosx 后端。QT4Agg 后端似乎同样缓慢。)
最佳答案
我认为速度减慢来自于 matplotlib 重新绘制整个图形,而不仅仅是您想要缩放的子图。我发现您可以通过创建多个图形并将它们嵌入到 PyQt 小部件中来加快速度。
这里有一个使用'figure_enter_event'
的快速概念证明和一些丑陋的黑客技术,以允许在所有图形中使用单个导航工具栏。请注意,我只是尝试使平移和缩放功能正常工作。通过查看 backend_bases.py
中 NavigationToolbar2
的源代码,我相信您可以根据您的需求进行调整。
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtCore import pyqtSlot
import matplotlib
matplotlib.use('Qt5Agg')
matplotlib.rcParams['backend.qt5'] = 'PyQt5'
matplotlib.rcParams.update({'figure.autolayout': True})
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import numpy as np
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, **kwargs):
super(MainWindow, self).__init__(**kwargs)
# Construct the plots
playout = QtWidgets.QGridLayout()
playout.setContentsMargins(0, 0, 0, 0)
for row in range(0, 10):
for col in range(0, 10):
fig = Figure()
ax = fig.add_subplot(111)
canvas = FigureCanvas(fig)
canvas.mpl_connect('figure_enter_event', self.enterFigure)
playout.addWidget(canvas, row, col, 1, 1)
t = np.arange(-2*np.pi, 2*np.pi, step=0.01)
ax.plot(t, np.sin(row*t) + np.cos(col*t))
# Assign toolbar to first plot
self.navbar = NavigationToolbar(playout.itemAtPosition(0, 0).widget(), self)
cwidget = QtWidgets.QWidget()
layout = QtWidgets.QVBoxLayout(cwidget)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(self.navbar)
layout.addLayout(playout)
self.setCentralWidget(cwidget)
def enterFigure(self, event):
self.navbar.canvas = event.canvas
event.canvas.toolbar = self.navbar
self.navbar._idDrag = event.canvas.mpl_connect('motion_notify_event', self.navbar.mouse_move)
# Toggle control off and then on again for the current canvas
if self.navbar._active:
if self.navbar._active == 'PAN':
self.navbar.pan()
self.navbar.pan()
elif self.navbar._active == 'ZOOM':
self.navbar.zoom()
self.navbar.zoom()
app = QtWidgets.QApplication(sys.argv)
win = MainWindow()
win.show()
app.exec_()
关于python - 当图形包含多个轴时,如何提高 matplotlib 中的滚动速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35003499/