python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > PyQt5 QtChart柱状图

PyQt5+QtChart实现柱状图的绘制

作者:SongYuLong的博客

QChart是一个QGraphicScene中可以显示的QGraphicsWidget。本文将利用QtChart实现柱状图的绘制,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下

柱状图分类

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柱状图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文