pythonpyqt5qtchartsqchart

How to add subplots in QtCharts?


I need to create two graphs (subplots, synchronous) and set the dimensions as follows:

Something like this sketch.

enter image description here

One chart is easy to create (code below). But to add the second subplot - it does not work. I tried to add it through QVBoxLayout() but also failed.

I found an example of what is needed, How to create Subplot using QCharts? but it is not written in Python (which causes trouble when trying to translate to Python). Here https://doc.qt.io/qt-5/qchart.html#chartType-prop is also not there, and also it is not in Python.

How to add a subplot and with the indication of the sizes (in pixels or in%)?

from random import uniform
from PyQt5.QtWidgets import QApplication, QMainWindow
import sys
from PyQt5.QtChart import QChart, QChartView, QLineSeries



class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(100, 100, 680, 500)
        self.create_linechart()
        self.show()

    def create_linechart(self):

        series = QLineSeries(self)
        for i in range(100):
            series.append(i, uniform(0, 10))

        chart = QChart()
        chart.addSeries(series)
        chart.createDefaultAxes()
        chartview = QChartView(chart)
        self.setCentralWidget(chartview)


App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec_())

Solution

  • You have to create 2 QChartView since in your code you only create and set it as centralwidget, then you must use a QWidget as a container and use a QVBoxLayout to add them, for the height ratio then you must set a stretch factor:

    from random import uniform
    import sys
    
    from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget
    from PyQt5.QtChart import QChart, QChartView, QLineSeries
    
    
    class Window(QMainWindow):
        def __init__(self):
            super().__init__()
            self.setGeometry(100, 100, 680, 500)
            view1 = self.create_linechart()
            view2 = self.create_linechart()
    
            central_widget = QWidget()
            self.setCentralWidget(central_widget)
            lay = QVBoxLayout(central_widget)
            lay.addWidget(view1, stretch=3)
            lay.addWidget(view2, stretch=1)
    
        def create_linechart(self):
            series = QLineSeries()
            for i in range(100):
                series.append(i, uniform(0, 10))
    
            chart = QChart()
            chart.addSeries(series)
            chart.createDefaultAxes()
            chartview = QChartView(chart)
            return chartview
    
    
    if __name__ == "__main__":
        App = QApplication(sys.argv)
        window = Window()
        window.show()
        sys.exit(App.exec_())
    

    enter image description here