氣輕PyQt5 41 QChart水平柱狀圖(QBarSet)
?
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtChart import QHorizontalBarSeries, QBarSet, QChart, QChartView, QValueAxis, QBarCategoryAxis
from math import ceil
import numpy as np
import sys
?
class PyQt541(QMainWindow):
??? def __init__(self):
??????? super().__init__()
??????? self.initUI()
?
??? def initUI(self):
??????? self.setWindowTitle("chart")
??????? self.resize(600, 400)?????????????????????????? # 設(shè)置窗口大小
?
??????? cityName = ['北京', '天津', '上海', '南京', '杭州', '青島', '廣州', '深圳', '重慶', '成都']
??????? yearData = ['2018', '2017'];
??????? gdpData=np.array([[30319.98, 28014.94],
????????????????????????? [18809.64, 18549.19],
????????????????????????? [32679.87, 30632.99],
????????????????????????? [12820.40, 11715.10],
????????????????????????? [13509.15, 12603.36],
????????????????????????? [12001.52, 11037.28],
??????????????? ??????????[22859.35, 21503.15],
????????????????????????? [24221.98, 22490.06],
????????????????????????? [20363.19, 19424.73],
????????????????????????? [15342.77, 13889.39]])
??????? MaxGDP = ceil(gdpData.max()/9)*10
?
??????? chart = QChart()??????????? ????????????????????# 圖表組件
??????? pen = QPen(QColor('#8B000'),3)????????????????? # 曲線顏色
??????? chart.setTitle("部分城市GDP")
??????? barSeries = QHorizontalBarSeries()
?
??????? gdp = list(gdpData.transpose())
??????? barDict = dict.fromkeys(yearData)
????? ??for i, value in enumerate(yearData):
??????????? barDict[value] = QBarSet(value)
??????????? barDict[value].append(gdp[i])
??????????? barSeries.append(barDict[value])
?
??????? chart.addSeries(barSeries)
?
??????? axis_x = QValueAxis()
??????? axis_x.setLabelFormat("%d")
??????? axis_x.setRange(0, MaxGDP)
??????? axis_x.setTitleText("億元")
??????? axis_x.setLinePen(pen)????????????????????????? # 設(shè)置X軸顏色和寬度
?
??????? axis_y = QBarCategoryAxis()???????????????????? # 柱狀圖坐標(biāo)
??????? axis_y.append(cityName)
?
??????? axis_y.setTitleText("城市")
??????? axis_y.setLinePen(pen)????????????????????????? # 設(shè)置Y軸顏色和寬度
??????? chart.addAxis(axis_x, Qt.AlignBottom)
?
??????? chart.addAxis(axis_y, Qt.AlignLeft)
?
??????? chartView = QChartView()??????????????????????? # 視圖組件
??????? chartView.setChart(chart)?????????????????????? # 顯示chart
??????? chartView.setRenderHint(QPainter.Antialiasing)? # 增加抗鋸齒
???????
??????? self.setCentralWidget(chartView)
?
??????? self.show()
?
if __name__ == '__main__':
??? app = QApplication(sys.argv)
??? window = PyQt541()
??? sys.exit(app.exec())
?
執(zhí)行結(jié)果
