首頁 > 軟體

PyQt5+QtChart實現柱狀圖的繪製

2022-12-17 14:00:36

柱狀圖分類

QBarSeries:豎向柱狀圖

QPercentBarSeries:豎向百分比柱狀圖

QStackedBarSeries:豎向堆疊柱狀圖

QHorizontalBarSeries:橫向柱狀圖

QHorizontalPercentBarSeries:橫向百分比柱狀圖

QHorizontalStackedBarSeries:橫向堆疊柱狀圖

實現程式碼

import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
from PyQt5.QtChart import QBarSet, QBarSeries, QChart, QChartView, QValueAxis, QBarCategoryAxis,
          QBarLegendMarker, QVBarModelMapper, QHBarModelMapper, QHorizontalBarSeries,QPercentBarSeries, 
          QHorizontalPercentBarSeries, QHorizontalStackedBarSeries,QStackedBarSeries

class MyBarWindow(QWidget):
    def __init__(self, parent=None):
        super(MyBarWindow, self).__init__(parent)

        chart = QChart()
        barSeries = QBarSeries()    # 豎向柱狀圖
        # barSeries = QPercentBarSeries()   # 豎向百分比柱狀圖
        # barSeries = QHorizontalBarSeries()    # 橫向柱狀圖
        # barSeries = QHorizontalPercentBarSeries()   # 橫向百分比柱狀圖
        # barSeries = QStackedBarSeries() # 豎向堆疊柱狀圖
        # barSeries = QHorizontalStackedBarSeries() # 橫向堆疊柱狀圖

        chartView = QChartView()
        valueAxisY = QValueAxis()
        barCategorAxisX = QBarCategoryAxis()

        chart.setAnimationOptions(QChart.AllAnimations)
        chart.setAnimationEasingCurve(QEasingCurve.OutBack)
        
        set0 = QBarSet("產品1")
        set1 = QBarSet("產品2")
        set2 = QBarSet("產品3")

        set0.append(10.12345)
        set0.append(3.23)
        set0.append(7)

        set1.append(5)
        set1.append(2)
        set1.append(9)

        set2.append(9)
        set2.append(1)
        set2.append(7)

        barSeries.append(set0)
        barSeries.append(set1)
        barSeries.append(set2)
        barSeries.setBarWidth(0.8)

        barSeries.setLabelsVisible(True)
        barSeries.setLabelsAngle(75.0)
        barSeries.setLabelsPrecision(3)
        # barSeries.setLabelsFormat("")
        
        barCategorAxisX.append(["一季度", "二季度", "三季度"])

        valueAxisY.setRange(0, 10)

        chart.setTitle("柱狀圖表")
        chart.setAxisX(barCategorAxisX)
        chart.setAxisY(valueAxisY)
        chart.addSeries(barSeries)

        chartView.setChart(chart)

        vbox = QVBoxLayout()
        vbox.addWidget(chartView)
        self.setLayout(vbox)
        

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MyBarWindow()
    win.show()
    sys.exit(app.exec_())

效果圖

豎向柱狀圖

豎向百分比柱狀圖

豎向堆疊柱狀圖

橫向柱狀圖

橫向百分比柱狀圖

橫向堆疊柱狀圖

到此這篇關於PyQt5+QtChart實現柱狀圖的繪製的文章就介紹到這了,更多相關PyQt5 QtChart柱狀圖內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com