Reputation: 659
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_()
Upvotes: 3
Views: 329
Reputation: 659
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))
...
Upvotes: 1