我试图通过允许用户鼠标点击位置来使用'ginput'来测量matplotlib图中的距离。我可以在matplotlib图中独立完成此操作,但是当我尝试将图形设置到matplotlib画布上然后将其嵌入到PyQt4小部件中时,我遇到了问题。下面是我的代码,其中大部分来自matplotlib示例。我的解决方案是单击一组位置,并将(x,y)坐标传递给'dist_calc'函数以获得距离。
import sys
from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import random
import numpy as np
class Window(QtGui.QWidget):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
self.fig = Figure((6.5, 5.0), tight_layout=True)
self.ax = self.fig.add_subplot(111)
self.canvas = FigureCanvas(self.fig)
self.toolbar = NavigationToolbar(self.canvas, self)
self.button = QtGui.QPushButton('Plot')
self.button.clicked.connect(self.plot)
self.ndist = QtGui.QPushButton('Measure')
self.ndist.clicked.connect(self.draw_line)
self.toolbar.addWidget(self.button)
self.toolbar.addWidget(self.ndist)
self.fig.tight_layout()
layout = QtGui.QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
self.setLayout(layout)
def plot(self):
data = [random.random() for i in range(20)]
self.ax.hold(False)
self.ax.plot(data, '*-')
self.canvas.draw()
def draw_line(self):
self.xy = plt.ginput(0)
x = [p[0] for p in self.xy]
y = [p[1] for p in self.xy]
self.ax.plot(x,y)
self.ax.figure.canvas.draw()
self.get_dist(x, y)
def get_dist(self, xpts, ypts):
npts = len(xpts)
distArr = []
for i in range(npts-1):
apt = [xpts[i], ypts[i]]
bpt = [xpts[i+1], ypts[i+1]]
dist =self.calc_dist(apt,bpt)
distArr.append(dist)
tdist = np.sum(distArr)
print(tdist)
def calc_dist(self,apt, bpt):
apt = np.asarray(apt)
dist = np.sum((apt - bpt)**2)
dist = np.sqrt(dist)
return dist
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
答案 0 :(得分:0)
一位领先的Matplotlib开发人员根据this comment,当你在Mattlotlib中嵌入Matplotlib时,你必须不导入pyplot
。 Pyplot设置了自己的gui,mainloop和canvas,它们干扰了Qt事件循环。
将行self.xy = plt.ginput(0)
更改为self.xy = self.fig.ginput(0)
并没有帮助,但却提出了一个有洞察力的错误:
AttributeError: 'FigureCanvasQTAgg' object has no attribute 'manager'
Figure.show works only for figures managed by pyplot, normally created by pyplot.figure().
简而言之,我不认为这是可能的。 ginput
是一个阻塞函数,似乎只是为Matplotlib事件循环实现的。我担心您必须使用Matplotlib mouse events构建所需的功能,在嵌入PyQt时执行工作。请务必不要使用pyplot!
修改:我记得,或许LassoSelector就是你所需要的。