簡體   English   中英

在 PyQT4 中修改 Matplotlib 圖形軸

[英]Modifying Matplotlib figure axes within PyQT4

我想創建一個在 PyQT4 GUI 中嵌入 Matplotlib 動畫的應用程序。 我試圖弄清楚 FigureCanvasQTAgg 對象如何工作的基礎知識,並且在創建后無法更改軸限制。 在下面的程序中,使用 FigureCanvasQTAgg 對象生成了一個非常簡單的圖形,我希望按下按鈕來更改結果圖的 x 軸的限制。 (請注意,下面的代碼是在最末尾代碼的簡化版本此篇。)

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()這行是做什么的。 Matplotlib 教程中,我得到的印象是這使得圖形實際上出現在 GUI 窗口中……但事實並非如此,因為當我注釋掉self.canvas.draw() ,圖形仍然出現在GUI 窗口。 實際上是self.setLayout(layout)self.setLayout(layout)圖形出現在 GUI 窗口中,這從我讀過的內容來看沒有意義。 似乎我對這個功能缺乏了解是我問題的根源......

我之前寫了一個簡單的應用程序。 根據我的經驗,必須在使用 matplotlib 功能更新設置或繪制曲線(或任何其他對象)后調用self.canvas.draw() 它只是一個觸發任何圖形對象更新的函數。 因此,只需將self.canvas.draw()添加到回調函數axis_adjust()的末尾axis_adjust()解決您的問題。

僅供參考,您的 UI 的層次結構將是QtGui.QDialog -> QtGui.QVBoxLayout -> FigureCanvas -> matplotlib.figure.Figure

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM