15
Сен
2021

Как построить два графика pyqtgraph в одном widget?

Имеется код:

import sys
from datetime import datetime
from PyQt5 import uic
from PyQt5 import QtCore, QtWidgets
from PyQt5.Qt import *

from docxtpl import DocxTemplate

from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg


class TimeAxisItem(pg.AxisItem):
    def tickStrings(self, values, scale, spacing):
        print(values, '\n', scale, '\n', spacing)
        return [datetime.fromtimestamp(value) for value in values]


class Widget(QMainWindow):
    def __init__(self):
        super().__init__()
        uic.loadUi("ui_lke2.1.ui", self)

        # Добавить/удалить строку в tableWidget_2
        # self.pushButton_7.clicked.connect(self.buttonAdd)
        # self.pushButton_8.clicked.connect(self.buttonDelete)
        # Добавить/удалить строку в tableWidget_3
        self.pushButton_9.clicked.connect(self.buttonAdd_2)
        self.pushButton_10.clicked.connect(self.buttonDelete_2)
        # Сохранить данные из таблицы tableWidget_3
        # self.pushButton.clicked.connect(self.buttonSave)
        # Создания графиков (Ph,Fe, CO2)
        self.pushButton_11.clicked.connect(self.buttonChart_Ph)


        for row in range(self.tableWidget_3.rowCount()):
            date_from = QtWidgets.QDateTimeEdit()
            date_from.setDateTime(
                QtCore.QDateTime(QtCore.QDate(2021, 8, 26),
                                 QtCore.QTime(15, 12, 33))
            )
            self.tableWidget_3.setCellWidget(row, 0, date_from)

        for row in range(self.tableWidget_3.rowCount()):
            date_from = QDateTimeEdit()
            date_from.setDateTime(
                QDateTime(QDate(2021, 9, 2))
            )
            date_from.dateTimeChanged.connect(
                lambda dateTime, row=row: self.date_changed(dateTime, row))
            self.tableWidget_3.setCellWidget(row, 0, date_from)

        self.dateTime0 = self.tableWidget_3.cellWidget(0, 0).dateTime()

    # Расчет времени от начального значения
    def date_changed(self, dateTime, row):
        if row == 0:
            self.dateTime0 = self.tableWidget_3.cellWidget(row, 0).dateTime()
            for row in range(1, self.tableWidget_3.rowCount()):
                dateTime2 = self.tableWidget_3.cellWidget(row, 0).dateTime()
                item = QTableWidgetItem()
                item.setData(Qt.DisplayRole,
                             self.dateTime0.secsTo(dateTime2) / 60. / 60.)
                self.tableWidget_3.setItem(row, 1, item)
            return

        dateTime2 = self.tableWidget_3.cellWidget(row, 0).dateTime()
        item = QTableWidgetItem()
        item.setData(Qt.DisplayRole,
                     self.dateTime0.secsTo(dateTime2) / 60. / 60.)
        self.tableWidget_3.setItem(row, 1, item)

    # Кнопка дабовляющая строку в таблицу tableWidget_2
    def buttonAdd(self):
        rowPosition = self.tableWidget_2.rowCount()
        self.tableWidget_2.insertRow(rowPosition)

    # Кнопка удаляющая строку в таблицу tableWidget_2
    def buttonDelete(self):
        if self.tableWidget_2.rowCount() > 0:
            self.tableWidget_2.removeRow(self.tableWidget_2.rowCount() - 1)

    # Кнопка дабовляющая строку в таблицу tableWidget_3
    def buttonAdd_2(self):
        rowPosition = self.tableWidget_3.rowCount()
        self.tableWidget_3.insertRow(rowPosition)
        date_from = QtWidgets.QDateTimeEdit()
        dateTime = QtCore.QDateTime().currentDateTime()
        date_from.setDateTime(dateTime)
        date_from.dateTimeChanged.connect(
            lambda dateTime, row=rowPosition:
            self.date_changed(dateTime, row))
        self.tableWidget_3.setCellWidget(rowPosition, 0, date_from)

    # Кнопка удаляющая строку в таблицу tableWidget_3
    def buttonDelete_2(self):
        if self.tableWidget_3.rowCount() > 0:
            self.tableWidget_3.removeRow(self.tableWidget_3.rowCount() - 1)

    # Сохранение данных из tableWidget_3
    def buttonSave(self):
        rows = self.tableWidget_3.rowCount()
        cols = self.tableWidget_3.columnCount()

        data_for_word = []
        for row in range(rows):
            tmp = []
            for col in range(cols):
                if col:
                    item = self.tableWidget_3.item(row, col)

                    if col == 1:
                        item = f'{float(item.text()):.0f}' if item else '0'
                    else:
                        item = item.text() if item else '0'
                else:
                    item = self.tableWidget_3.cellWidget(row, 0). \
                        dateTime().toString('dd.MM.yyyy hh:mm')
                tmp.append(item)

            data_for_word.append(tmp)

        for i in data_for_word: print(i)

        self.buttonLoader(data_for_word)

    # Загрузка данных в шаблон Word
    def buttonLoader(self, data):
        data_for_word = []

        for item in data:
            if any(item):
                data_for_word.append({
                    "data": item[0],
                    "time": item[1],
                    "ph": item[2],
                    "ph2": item[3],
                    "fe": item[4],
                    "pm": item[5],
                    "co2": item[6],
                    "pm2": item[7],
                    "pm3": item[8]
                })

        print()
        for i in data_for_word: print(i)

        doc = DocxTemplate('test_word.docx')
        context = {
            'tbl_contents': data_for_word
        }
        doc.render(context)
        doc.save('test2.docx')

    def buttonChart_Ph(self):
        data_for_word = []

        rows = self.tableWidget_3.rowCount()
        for row in range(rows):
            item_N2 = self.tableWidget_3.item(row, 1)
            _data_N2 = item_N2.data(Qt.DisplayRole) if item_N2 else '0'
            item_N3 = self.tableWidget_3.item(row, 2)
            _data_N3 = item_N3.data(Qt.DisplayRole) if item_N3 else '0'
            data_for_word.append([_data_N2, _data_N3])

        self.x, self.y = [], []
        for x, y in data_for_word:
            print(f'x={x}; y={y}')
            self.x.append(float(x))
            self.y.append(float(y))

        self.widget = pg.PlotWidget()
        pen = pg.mkPen(color=(255, 0, 0), width=2)
        self.widget.plot(
            x=self.x,
            y=self.y, pen=pen, symbol='o'
        )

        w = self.findChild(PlotWidget, 'widget')

        print(f'w --> {w}')
        if w:
            w.deleteLater()
        self.gridLayout_8.addWidget(
            self.widget,
            0, 0, 1, 1,
            alignment=Qt.AlignCenter
        )
        # Фиксация размера widget
        self.widget.setFixedSize(260, 238)
        # Смена цвета графика на белый
        self.widget.setBackground('w')
        # Название графика widget
        self.widget.setTitle("Ph, ед.Ph", color="b", size="10pt")
        # Добовляются названия осей координат
        styles = {"color": "#f00", "font-size": "15px"}
        self.widget.setLabel("left", "Ph", **styles)
        self.widget.setLabel("bottom", "Hour(H)", **styles)

        self.widget.showGrid(x=True, y=True)

        self.buttonChart_Fe()


    def buttonChart_Fe(self):
        data_for_word = []

        rows = self.tableWidget_3.rowCount()
        for row in range(rows):
            item_N2 = self.tableWidget_3.item(row, 1)
            _data_N2 = item_N2.data(Qt.DisplayRole) if item_N2 else '0'
            item_N3 = self.tableWidget_3.item(row, 4)
            _data_N3 = item_N3.data(Qt.DisplayRole) if item_N3 else '0'
            data_for_word.append([_data_N2, _data_N3])

        self.x, self.y = [], []
        for x, y in data_for_word:
            print(f'x={x}; y={y}')
            self.x.append(float(x))
            self.y.append(float(y))

        self.widget_2 = pg.PlotWidget()
        pen = pg.mkPen(color=(255, 0, 0), width=2)
        self.widget_2.plot(
            x=self.x,
            y=self.y, pen=pen, symbol='o'
        )

        w = self.findChild(PlotWidget, 'widget')

        print(f'w --> {w}')
        if w:
            w.deleteLater()
        self.gridLayout_10.addWidget(
            self.widget_2,
            0, 0, 1, 1,
            alignment=Qt.AlignCenter
        )
        # Фиксация размера widget
        self.widget_2.setFixedSize(260, 238)
        # Смена цвета графика на белый
        self.widget_2.setBackground('w')
        # Название графика widget
        self.widget_2.setTitle("C(Fe общ.), мг/дм3", color="b", size="10pt")
        # Добовляются названия осей координат
        styles = {"color": "#f00", "font-size": "15px"}
        self.widget_2.setLabel("left", "Fe", **styles)
        self.widget_2.setLabel("bottom", "Hour(H)", **styles)

        self.widget_2.showGrid(x=True, y=True)

        self.buttonChart_CO2()



    def buttonChart_CO2(self):
        data_for_word = []

        rows = self.tableWidget_3.rowCount()
        for row in range(rows):
            item_N2 = self.tableWidget_3.item(row, 1)
            _data_N2 = item_N2.data(Qt.DisplayRole) if item_N2 else '0'
            item_N3 = self.tableWidget_3.item(row, 6)
            _data_N3 = item_N3.data(Qt.DisplayRole) if item_N3 else '0'
            data_for_word.append([_data_N2, _data_N3])

        self.x, self.y = [], []
        for x, y in data_for_word:
            print(f'x={x}; y={y}')
            self.x.append(float(x))
            self.y.append(float(y))

        self.widget_3 = pg.PlotWidget()
        pen = pg.mkPen(color=(255, 0, 0), width=2)
        self.widget_3.plot(
            x=self.x,
            y=self.y, pen=pen, symbol='o'
        )

        w = self.findChild(PlotWidget, 'widget')

        print(f'w --> {w}')
        if w:
            w.deleteLater()
        self.gridLayout_11.addWidget(
            self.widget_3,
            0, 0, 1, 1,
            alignment=Qt.AlignCenter
        )
        # Фиксация размера widget
        self.widget_3.setFixedSize(260, 238)
        # Смена цвета графика на белый
        self.widget_3.setBackground('w')
        # Название графика widget
        self.widget_3.setTitle("C(CO2), мг/дм3", color="b", size="10pt")
        # Добовляются названия осей координат
        styles = {"color": "#f00", "font-size": "15px"}
        self.widget_3.setLabel("left", "CO2", **styles)
        self.widget_3.setLabel("bottom", "Hour(H)", **styles)

        self.widget_3.showGrid(x=True, y=True)

        self.buttonChart_PhFe()

    def buttonChart_PhFe(self):
        pass



if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setStyle("Windows")
    ex = Widget()
    ex.setWindowTitle("SAFTD (The system of automatic filling of template documents)")
    ex.setFixedSize(640, 540)
    ex.show()
    sys.exit(app.exec_())

Нужно что бы в функции def buttonChartPhFe строились два графика в одном widget.


Код ui:

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>640</width>
    <height>498</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QGridLayout" name="gridLayout">
    <item row="0" column="0">
     <widget class="QTabWidget" name="tabWidget">
      <widget class="QWidget" name="tab">
       <attribute name="title">
        <string>Tab 1</string>
       </attribute>
       <layout class="QGridLayout" name="gridLayout_5">
        <item row="0" column="0">
         <widget class="QTableWidget" name="tableWidget_3">
          <row>
           <property name="text">
            <string>1</string>
           </property>
          </row>
          <column>
           <property name="text">
            <string>1</string>
           </property>
          </column>
          <column>
           <property name="text">
            <string>2</string>
           </property>
          </column>
          <column>
           <property name="text">
            <string>3</string>
           </property>
          </column>
          <column>
           <property name="text">
            <string>4</string>
           </property>
          </column>
          <column>
           <property name="text">
            <string>5</string>
           </property>
          </column>
          <column>
           <property name="text">
            <string>6</string>
           </property>
          </column>
          <column>
           <property name="text">
            <string>7</string>
           </property>
          </column>
          <column>
           <property name="text">
            <string>8</string>
           </property>
          </column>
          <column>
           <property name="text">
            <string>9</string>
           </property>
          </column>
         </widget>
        </item>
        <item row="1" column="0">
         <layout class="QGridLayout" name="gridLayout_21">
          <item row="0" column="1">
           <widget class="QGroupBox" name="groupBox">
            <property name="title">
             <string>GroupBox</string>
            </property>
            <layout class="QGridLayout" name="gridLayout_4">
             <item row="2" column="0">
              <widget class="QPushButton" name="pushButton_11">
               <property name="text">
                <string>Просмотреть график</string>
               </property>
              </widget>
             </item>
             <item row="0" column="0">
              <widget class="QPushButton" name="pushButton_9">
               <property name="text">
                <string>Добавить </string>
               </property>
              </widget>
             </item>
             <item row="1" column="0">
              <widget class="QPushButton" name="pushButton_10">
               <property name="text">
                <string>Удалить</string>
               </property>
              </widget>
             </item>
            </layout>
           </widget>
          </item>
          <item row="0" column="0">
           <widget class="QTabWidget" name="tabWidget_2">
            <property name="currentIndex">
             <number>0</number>
            </property>
            <widget class="QWidget" name="tab_3">
             <attribute name="title">
              <string>График</string>
             </attribute>
             <layout class="QGridLayout" name="gridLayout_3">
              <item row="0" column="0">
               <layout class="QGridLayout" name="gridLayout_8">
                <item row="0" column="0">
                 <widget class="QWidget" name="widget" native="true"/>
                </item>
               </layout>
              </item>
             </layout>
            </widget>
            <widget class="QWidget" name="tab_4">
             <attribute name="title">
              <string>Tab 2</string>
             </attribute>
             <layout class="QGridLayout" name="gridLayout_6"/>
            </widget>
           </widget>
          </item>
         </layout>
        </item>
       </layout>
      </widget>
      <widget class="QWidget" name="tab_2">
       <attribute name="title">
        <string>Tab 2</string>
       </attribute>
      </widget>
     </widget>
    </item>
   </layout>
  </widget>
  <widget class="QMenuBar" name="menubar">
   <property name="geometry">
    <rect>
     <x>0</x>
     <y>0</y>
     <width>640</width>
     <height>21</height>
    </rect>
   </property>
  </widget>
  <widget class="QStatusBar" name="statusbar"/>
 </widget>
 <resources/>
 <connections/>
</ui>

Пример графика

Источник: https://ru.stackoverflow.com/questions/1328792/%D0%9A%D0%B0%D0%BA-%D0%BF%D0%BE%D1%81%D1%82%D1%80%D0%BE%D0%B8%D1%82%D1%8C-%D0%B4%D0%B2%D0%B0-%D0%B3%D1%80%D0%B0%D1%84%D0%B8%D0%BA%D0%B0-pyqtgraph-%D0%B2-%D0%BE%D0%B4%D0%BD%D0%BE%D0%BC-widget

Тебе может это понравится...

Добавить комментарий