PyQtGraph之柱狀圖

星空28發表於2024-06-13
from PyQt5.QtWidgets import *
import pyqtgraph as pg
import sys


class MainWindow(QWidget):

    def __init__(self):
        super().__init__()

        self.setWindowTitle('pyqtgraph作圖示例')

        # 建立 PlotWidget 物件
        self.pw = pg.PlotWidget()
        # 設定圖表標題
        self.pw.setTitle("訂單數量",color='#008080',size='12pt')
        # 背景色改為白色
        self.pw.setBackground('w')
        # 設定上下左右的label
        self.pw.setLabel("left", "訂單量(條)")
        self.pw.setLabel("bottom", "日期")

        # 顯示錶格線
        self.pw.showGrid(x=True, y=True)

        # 產生兩種柱狀圖資料,分別對應 紅色柱 和藍色柱
        x1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        y1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        x2 = [0.33, 1.33, 2.33, 3.33, 4.33, 5.33, 6.33, 7.33, 8.33, 9.33]
        y2 = [0.33, 1.33, 2.33, 3.33, 4.33, 5.33, 6.33, 7.33, 8.33, 9.33]

        bg1 = pg.BarGraphItem(x=x1, height=y1, width=0.3, brush='r')
        bg2 = pg.BarGraphItem(x=x2, height=y2, width=0.3, brush='g')

        # 新增到介面上
        self.pw.addItem(bg1)
        self.pw.addItem(bg2)


        # 建立其他Qt控制元件
        okButton = QPushButton("OK")
        lineEdit = QLineEdit('點選資訊')
        # 水平layout裡面放 edit 和 button
        hbox = QHBoxLayout()
        hbox.addWidget(lineEdit)
        hbox.addWidget(okButton)

        # 垂直layout裡面放 pyqtgraph圖表控制元件 和 前面的水平layout
        vbox = QVBoxLayout()
        vbox.addWidget(self.pw)
        vbox.addLayout(hbox)

        # 設定全域性layout
        self.setLayout(vbox)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = MainWindow()
    main.show()
    app.exec_()

相關文章