PyQt5 QtChart-QLineSeries 折线图
- QLineSeries
QLineSeries
QLineSeries类将数据序列显示为折线图,其核心代码:
lineSeries = QLineSeries()
lineSeries.append(1, 3)
lineSeries.append(5, 8)
…
chart.addSeries(lineSeries)
常用方法:
- setPointsVisible(True) :设置数据点显示状态
- setPointLabelsVisible(True):设置数据点标签显示状态
- setPointLabelsFormat(“(@xPoint, @yPoint)”):设置数据点标签格式
- setPointLabelsFont(QFont(None, 8)) :设置数据点标签字体
- setPointLabelsColor(QColor(255, 0,0)) :设置数据点标签颜色
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtChart import *
import random
class MyWaveWindow(QWidget):
def __init__(self, parent=None):
super(MyWaveWindow, self).__init__(parent)
self.setWindowTitle("折线图")
# 创建图表 并设置相关参数
chart = QChart()
chart.setTitle("随机折线图")
chart.setAnimationOptions(QChart.SeriesAnimations)
chart.setAnimationDuration(1000)
chart.setAnimationEasingCurve(QEasingCurve.InOutCirc)
# chart.setTheme(QChart.ChartThemeBlueCerulean)
chart.legend().show()
# 创建折线数据序列
lineSeries = QLineSeries()
for value in range(0, 100):
lineSeries.append(value, round(random.random()*10, 2))
lineSeries.setPointsVisible(True)
lineSeries.setPointLabelsVisible(True)
lineSeries.setPointLabelsFormat("(@xPoint, @yPoint)")
lineSeries.setPointLabelsFont(QFont(None, 8))
lineSeries.setPointLabelsColor(QColor(255, 0, 0))
chart.addSeries(lineSeries)
# 创建轴坐标
# chart.createDefaultAxes() # 创建默认轴
axis_x = QValueAxis()
axis_x.setLabelFormat("%d")
axis_x.setMinorTickCount(3)
axis_x.setRange(0, 100)
chart.addAxis(axis_x, Qt.AlignBottom)
lineSeries.attachAxis(axis_x)
axis_y = QValueAxis()
axis_y.setLabelFormat("%d")
# axis_y.setTickType(QValueAxis.TicksDynamic)
axis_y.setTickCount(20)
axis_y.setMinorTickCount(3)
axis_y.setRange(0, 10)
chart.addAxis(axis_y, Qt.AlignLeft)
lineSeries.attachAxis(axis_y)
chartView = QChartView(chart)
chartView.setRenderHint(QPainter.Antialiasing)
layout = QVBoxLayout()
layout.addWidget(chartView)
self.setLayout(layout)
self.resize(800, 600)
if __name__ == "__main__":
app = QApplication(sys.argv)
win = MyWaveWindow()
win.show()
app.exit(app.exec_())