【问题标题】:Show matplotlib plots from the list in PYQT5 layout从 PYQT5 布局的列表中显示 matplotlib 图
【发布时间】:2021-09-21 20:30:47
【问题描述】:

我有使用 matplotlib 绘制的数字列表。

# x, y1, y2, y3 array of points.    
list_of_plots = []
for i in range(0, 100, 1):
    x, y1, y2, y3 = get_points_array(i)

    fig = plt.figure(i)
    plt.plot(x, y1, '--rs', label='y1')
    plt.plot(x, y2, '-g*', label='y2')
    plt.plot(x, y3, ':bo', label='y3')

    list_of_plots.append(fig)
    plt.close()

通过这段代码,我得到了不同地块的列表。

print(list_of_plots)

图形大小 640x480 带 1 个轴>, ,, ,, ,...

我有一个由 PyQT5 制作的 GUI。我想在 QHBoxLayout 中显示 3 个特定的图

self.second_row = QtWidgets.QHBoxLayout()
#list_of_plots[0], list_of_plots[1], list_of_plots[2] will show inside second_row.

我查遍了互联网,但找不到任何线索。我不想将图形保存为 .png 格式,然后在布局上显示,因为过多图像的积累会导致内存大小不足。

【问题讨论】:

    标签: python matplotlib pyqt pyqt5


    【解决方案1】:

    你必须使用matplotlib提供的Qt的FigureCanvas,这是一个使用Figure进行绘画的QWidget:

    import sys
    
    from PyQt5.QtWidgets import QApplication, QHBoxLayout, QWidget
    
    import numpy as np
    
    from matplotlib.backends.backend_qt5agg import FigureCanvas
    from matplotlib.figure import Figure
    
    
    def get_points_array(i):
        x = np.arange(0, 2 * i + 10, 0.1)
        y1 = x * np.sin(x) * np.exp(-x)
        y2 = x * np.sin(x)
        y3 = x * np.cos(x)
        return x, y1, y2, y3
    
    
    class Widget(QWidget):
        def __init__(self, parent=None):
            super().__init__(parent)
    
            lay = QHBoxLayout(self)
    
            for i in range(3):
                x, y1, y2, y3 = get_points_array(i)
                canvas = FigureCanvas(Figure(figsize=(5, 3)))
                ax = canvas.figure.subplots()
                ax.plot(x, y1, "--rs", label="y1")
                ax.plot(x, y2, "-g*", label="y2")
                ax.plot(x, y3, ":bo", label="y3")
    
                lay.addWidget(canvas)
    
    
    def main():
        app = QApplication(sys.argv)
        window = Widget()
        window.show()
        app.exec_()
    
    
    if __name__ == "__main__":
        main()
    

    【讨论】:

    • 感谢您的回答。但是,我正在寻找类似的东西,而不是直接绘制并放入布局,首先存储所有图(在这种情况下 list_of_plots 包含所有已经绘制的图形)然后从列表中放置布局。这样,我可以立即更新可见页面,而无需每次刷新时都花时间绘制。
    • @justRandomLearner 我不知道你从哪里得到解决方案,但这是不可能的。我建议你检查 matplotlib 是如何工作的,以及它是如何在 Qt 中绘制的。
    • 我明白了。我没有从某个地方得到它,这是我认为可以克服我的问题的方法,但是由于我是 PyQt5 的新手,所以它似乎是错误的方法。谢谢你的建议。如果您有任何建议可以有效地绘制单个页面的数百个图并在每次单击按钮时进行更改,欢迎您! (:
    • @justRandomLearner 你显然有一个XY Problem
    • 你是对的。我没有清楚地解释我的问题,而只是解释了我的解决方法。不管怎样,我从你的建议中学到了一些东西。再次感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    相关资源
    最近更新 更多