亲宝软件园·资讯

展开

PyQt5+QtChart实现柱状图的绘制

SongYuLong的博客 人气:0

柱状图分类

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

效果图

竖向柱状图

竖向百分比柱状图

竖向堆叠柱状图

横向柱状图

横向百分比柱状图

横向堆叠柱状图

加载全部内容

相关教程
猜你喜欢
用户评论