简体   繁体   中英

Problem between Matplotlib figure & the PyQt5/PySide2 QSplitter Widget

I am trying to create 2 plot figures that can be auto-resized with the PyQt5/PySide2 QSplitter Widget. However, when I shrink the plots, their title and x-axis labels get overlapped, as shown below. It looks broken. Does anyone know better tricks to solve this problem?

Here is my sample code

import numpy as np
from PySide2 import QtWidgets, QtCore
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
import matplotlib
matplotlib.use('Qt5Agg')


class MyChart(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()

        canvas1 = FigureCanvasQTAgg(Figure(figsize=(20,12))) 
        ax1 = canvas1.figure.add_subplot(111)
        ax1.plot(np.sin(np.linspace(0, 4, 1000)))
        ax1.set_title('Chart 1')

        canvas2 = FigureCanvasQTAgg(Figure(figsize=(20,12))) 
        ax2 = canvas2.figure.add_subplot(111)
        ax2.plot(np.sin(5 * np.linspace(0, 4, 1000)))
        ax2.set_title('Chart 2')
        
        splitter = QtWidgets.QSplitter(QtCore.Qt.Vertical)
        splitter.addWidget(canvas1)
        splitter.addWidget(canvas2)
        self.setCentralWidget(splitter)
        self.show()

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    w = MyChart()
    app.exec_()

在此处输入图片说明

Thanks to Jody from the matplotlib forum , the solution was much simpler than I though. Just include constrained_layout=True in the figure constructor and that's it!! Here is the outcome.

...
canvas1 = FigureCanvasQTAgg(Figure(figsize=(20,12), constrained_layout=True)) 
...
canvas2 = FigureCanvasQTAgg(Figure(figsize=(20,12), constrained_layout=True)) 
...

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM