简体   繁体   中英

How to add subplots in QtCharts?

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

  • the upper graph is 75% of the output area
  • and the lower graph is 25% of the height of the output area.

Something like this sketch.

在此处输入图像描述

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_())

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_())

在此处输入图像描述

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