【问题标题】:Matplotlib plot in PyQt5 UI doesn't update when the plot is changed [closed]PyQt5 UI 中的 Matplotlib 绘图在绘图更改时不会更新 [关闭]
【发布时间】:2020-10-26 19:05:28
【问题描述】:

我正在开发 Python/Qt5 项目,我使用 matplotlib 来渲染一些绘图,我遇到的问题是,在使用新绘图更新此小部件后,在我调整窗口大小之前,图形不会更新,问题是类似于this,但该解决方案对我不起作用。我创建了一个自定义小部件来包含 matplotlib 图,在 Qt Designer 中添加了一个空小部件并将其提升为这个自定义小部件:

from matplotlib.backends.qt_compat import QtCore, QtWidgets
from matplotlib.backends.backend_qt5agg import (FigureCanvas, NavigationToolbar2QT as NavigationToolbar)
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

class PlotWidget(FigureCanvas):
    def __init__(self, parent=None):
        plt.style.use('dark_background')
        self.figure = plt.figure()
        FigureCanvas.__init__(self, self.figure)
        self.setParent(parent)

为了绘图,我使用了另一个模块中的一些类,例如,这是一个制作其中一个绘图的函数:

def plot_fft_spectrogram(self, widget, symmetric=False):
    fft_x, fft_y = self.fft(symmetric=symmetric)

    widget.figure, axis = plt.subplots(1,1)
    axis.plot(fft_x, fft_y)
    axis.grid(ls=':')
    axis.set_xlabel('Frequency (Hz)')
    axis.set_ylabel('Amplitude')
    widget.figure.tight_layout()
    #This is the solution from the thread
    widget.figure.canvas.draw_idle()

这个函数是从我的mainwindow.py 调用的,当调用这个绘图函数时,它会将self.ui.plot_widget(这是带有matplotlib 图形的自定义小部件)作为widget argument 传递:

self.fourier_analyzer.plot_fft_spectrogram(self.ui.plot_widget, symmetric=symmetric)

我尝试了上述线程中描述的答案,但没有奏效。在我调整窗口大小之前,该数字不会更新。我的问题是如何自动更新其中包含的 Qt 小部件或 matplotlib 图形?

【问题讨论】:

标签: python matplotlib pyqt pyqt5


【解决方案1】:

如果没有可重现的示例,很难提供帮助,但我的建议是不要从 FigureCanvas 继承,因为它似乎会造成一些混乱。

为了设置你可以使用的绘图风格,

with plt.style.context("dark_background"):
    # your plot goes here

话虽如此,在您的代码中,当您创建子图时,您将覆盖 widget.figure,并且这样做会丢失对在 FigureCanvas.__init__(self, self.figure) 中启动的图形的引用。

您可以尝试添加子图,

axis = widget.figure.add_subplot(111)

【讨论】:

  • 使用axis = widget.figure.add_subplot(111)居然解决了问题,谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-10-13
  • 2022-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
相关资源
最近更新 更多