首頁 > 軟體

PyQt5+QtChart實現繪製曲線圖

2022-12-17 14:00:35

QSplineSeries

QSplineSeries類將資料序列顯示為曲線圖。核心程式碼:

spline = QSplineSeries()
spline.append(0, 23)
spline.append(1, 56)

chart.addSeries(lineSeries)

常用方法

  • setPointsVisible(True) :設定資料點顯示狀態
  • setPointLabelsVisible(True):設定資料點標籤顯示狀態
  • setPointLabelsFormat(“(@xPoint, @yPoint)”):設定資料點標籤格式
  • setPointLabelsFont(QFont(None, 8)) :設定資料點標籤字型
  • setPointLabelsColor(QColor(255, 0,0)) :設定資料點標籤顏色

實現程式碼

import random
import sys

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
from PyQt5.QtChart import QSplineSeries, QLineSeries, QChart, QChartView, QValueAxis


class MySplineWindow(QWidget):
    def __init__(self, parent=None):
        super(MySplineWindow, self).__init__(parent)
        self.setWindowTitle("曲線圖表演示")

        chart = QChart()
        chart.setTitle("曲線圖表")
        chart.setAnimationDuration(1500)
        chart.setAnimationOptions(QChart.SeriesAnimations)
        chart.setAnimationEasingCurve(QEasingCurve.OutCirc)
        chart.legend().show()

        spline = QSplineSeries()
        for value in range(1, 50):
            spline.append(value, round(random.random()*100))


        spline.setName("隨機噪聲")
        # spline.setColor(Qt.blue)
        spline.setPointsVisible(True)
        spline.setPointLabelsVisible(True)
        spline.setPointLabelsFormat("(@xPoint, @yPoint)")
        spline.setPointLabelsFont(QFont(None, 6))
        spline.setPointLabelsColor(Qt.darkBlue)
                
        chart.addSeries(spline)
        chart.createDefaultAxes()

        axis_x = QValueAxis()
        axis_x.setLabelFormat("%d")
        chart.addAxis(axis_x, Qt.AlignBottom)
        spline.attachAxis(axis_x)

        chartView = QChartView()
        chartView.setChart(chart)
        chartView.setRenderHint(QPainter.Antialiasing)
        
        vbox = QVBoxLayout()
        vbox.addWidget(chartView)
        self.setLayout(vbox)


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

效果圖

增加抗鋸齒:chartView.setRenderHint(QPainter.Antialiasing)

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


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