我想創建一個在PyQT4 GUI中嵌入Matplotlib動畫的應用程序。我試圖找出FigureCanvasQTAgg對象如何工作的基礎知識,並且在創建軸限制後無法更改軸限制。在下面的程序中,使用FigureCanvasQTAgg對象生成一個非常簡單的圖形,並且我希望按下該按鈕來更改結果圖的x軸的極限。 (請注意,下面的代碼是代碼的在this post末的簡化版本。)在PyQT4中修改Matplotlib圖形軸
import sys
from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class Window(QtGui.QDialog):
def __init__(self):
super(Window, self).__init__()
self.fig = Figure()
self.canvas = FigureCanvas(self.fig)
self.ax = self.fig.add_subplot(111) # create an axis
self.ax.hold(False) # discards the old graph
self.ax.set_xlim([0, 100])
self.ax.set_ylim([-10, 10])
self.ax.set_xlabel('Random x label')
self.button = QtGui.QPushButton('Adjust axes')
self.button.clicked.connect(self.axis_adjust)
# set the layout
layout = QtGui.QVBoxLayout()
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
self.canvas.draw()
def axis_adjust(self):
self.ax.set_xlim([0, 200])
self.ax.set_xlabel('New label')
app = QtGui.QApplication(sys.argv)
ex = Window()
sys.exit(app.exec_())
不幸的是,當我運行了一個程序,然後單擊「調整軸」按鈕,它絕對沒有影響。我基本上不明白的一件事是self.canvas.draw()
行。從a Matplotlib tutorial,我得到這樣的印象,這使得圖形實際上出現在GUI窗口內......但情況並非如此,因爲當我註釋行self.canvas.draw()
時,圖形仍然出現在GUI窗口內。它實際上是self.setLayout(layout)
,它使圖形出現在GUI窗口中,這與我所閱讀的內容無關。看來我對這個功能缺乏瞭解是我的問題的根源...
這做到了 - 謝謝! – dyson