[PyQt5] PyQtChart two-dimensional drawing

1. Overview
PyQtChart is a Python binding for the Qt Charts module, which needs to be installed separately. Draw various common two-dimensional charts, such as line charts, histograms, pie charts, scatter plots, polar plots, etc.

To install PyQtChart, just execute the following command in the Windows cmd window.

pip3 install PyQtChart

The installed classes of PyQtChart are all in the PyQt5.QtChart module, so when the classes are to be used in the program, the import statement example is as follows:

from PyQt5.QtChart import QChartView,QChart,QLineSeries,QValueAxis

2. Main classes
The PyQtChart module includes a set of easy-to-use chart manipulation classes, which are based on Qt's Graphics View architecture, and its core components are QChartView and QChart.

(1) The parent class of QChartView is QGraphicsView, which is the view class in the Graphics View architecture. Therefore, QChartView is a view for displaying charts. First place a QGraphicsView component, and then promote it to QChartView. There are few functions defined by the QChartView class, only the following.

setChart(chart) function, set a QChart object chart as the displayed chart.
The chart() function returns the current QChart class object of QChartView.
The setRubberBand(rubberBand) function sets the type of the selection box, that is, the way the mouse drags the selection range on the view component. The parameter rubberBand is a combination of QChartView.RubberBand enumeration types. The enumeration types have the following values: QChartView
. NoRubberBand (no selection box);
QChartView.VerticalRubberBand (vertical selection);
QChartView.HorizontalRubberBand (horizontal selection);
QChartView.RectangleRubberBand (rectangular box selection).
The rubberBand() function returns the selected box type.

(2) The inheritance relationship of QChart is shown in the figure. It can be seen that QChart is inherited from QGraphicsItem, so QChart is a kind of graphic item. QPolarChart is a chart class for drawing polar charts, which inherits from QChart.

The inheritance relationship of QChart:
insert image description here
(3) Sequence: The type of chart is mainly determined by the type of sequence. Common chart types include line chart, histogram, pie chart, scatter chart, etc., and the hierarchical relationship of sequence classes in the PyQtChart module as the picture shows. The QAbstractSeries class is the upper class of all these classes. The parent class of QAbstractSeries is QObject, so these sequence classes are not visual components, but classes for managing various types of sequence data.
insert image description here
These sequence classes can be divided into the following groups.
(1) The curve and scatter class
QLineSeries polyline sequence inherited from QXYSeries: a sequence directly connected by a straight line between two data points, used for general curve display, Demo12_1 is this type.
QSplineSeries curve sequence: The connection of data points will be smoothed.
QScatterSeries scatter series: only shows the series of data points.
(2) Various histogram classes QBarSeries and QHorizontalBarSeries inherited from QAbstractBarSeries
: common histogram sequences.
QStackedBarSeries and QHorizontalStackedBarSeries: series of stacked bar charts.
QPercentBarSeries and QHorizontalPercentBarSeries: Percentage histogram series.
(3) The special sequence class QPieSeries directly inherited from QAbstractSeries
is a pie chart sequence.
QCandlestickSeries Candlestick Sequence: Can draw candlesticks commonly used in financial data analysis.
QBoxPlotSeries box plot sequence: a graphic for financial data analysis.
QAreaSeries area chart sequence: Draw a filled area chart using two QLineSeries series curves as upper and lower bounds.

Coordinate axis : The coordinate axis uses the numerical coordinate axis of the QValueAxis class. If logarithmic coordinates are used, the coordinate axis of the QLogValueAxis class can be used. The abscissa of the histogram is often the category represented by the text, and QBarCategoryAxis can be used as the abscissa, while the pie chart has no coordinate axis.
The coordinate axis classes in PyQtChart are as follows:
QValueAxis numerical coordinate axis: as the coordinate axis of numerical data
QCategoryAxis grouping numerical coordinate axis: text labels can be set for the numerical range
QLogValueAxis logarithmic numerical coordinate axis: as the logarithmic coordinate axis of numerical data, The base of the logarithm can be set.
QBarCategoryAxis category axis: Use a string as the scale of the axis, used for the non-numeric axis of the chart.
QDateTimeAxis date and time axis: as the axis of date and time data, the
Inheritance relationship of coordinate axis class
parent class of the QAbstractAxis class is QObject, so the axis class is not a visible component class, but is used to encapsulate various data and properties related to the axis, such as the scale of the axis , labels, gridlines, titles, and more.

Legend (Legend) : QLegend is a class that encapsulates the legend function. After the sequence is added to the QChart object, the legend will be automatically generated. The text in the legend can be set for each sequence, and the legend can be displayed on the top, bottom, left, and right of the chart. different locations.

3. Detailed code
Create a GUI application based on QMainWindow in pure code, and draw a simple chart with several main classes in the PyQtChart module. The complete code of the myMainWindow.py file is as follows:

import sys, math
from PyQt5.QtWidgets import  QApplication, QMainWindow
from PyQt5.QtChart import QChartView,QChart,QLineSeries,QValueAxis

class QmyMainWindow(QMainWindow): 
   def __init__(self, parent=None):
      super().__init__(parent)
      self.setWindowTitle("Demo12_1, QChart基本绘图")
      self.resize(580,420)
##创建chart和chartView
      chart = QChart()               #创建 chart
      chart.setTitle("简单函数曲线")
      chartView=QChartView(self)     #创建 chartView
      chartView.setChart(chart)      #chart添加到chartView
      self.setCentralWidget(chartView)
##创建曲线序列
      series0 = QLineSeries()
      series1 = QLineSeries()
      series0.setName("Sin曲线")
      series1.setName("Cos曲线")
      chart.addSeries(series0)       #序列添加到图表
      chart.addSeries(series1)
##序列添加数值
      t=0
      intv=0.1
      pointCount=100
      for i in range(pointCount):
         y1=math.cos(t) 
         series0.append(t,y1)
         y2=1.5*math.sin(t+20)
         series1.append(t,y2)
         t=t+intv
##创建坐标轴
      axisX = QValueAxis()      #x轴
      axisX.setRange(0, 10)     #设置坐标轴范围
      axisX.setTitleText("time(secs)")    #轴标题
      axisY = QValueAxis()      #y轴
      axisY.setRange(-2, 2)
      axisY.setTitleText("value")
##为序列设置坐标轴
      chart.setAxisX(axisX, series0)    #为序列series0设置坐标轴
      chart.setAxisY(axisY, series0)
      chart.setAxisX(axisX, series1)    #为序列series1设置坐标轴
      chart.setAxisY(axisY, series1)

##  ============窗体测试程序 ============================
if  __name__ == "__main__": 
   app = QApplication(sys.argv)
   form = QmyMainWindow() 
   form.show()
   sys.exit(app.exec_())

(1) First create a QChart object chart and a QChartView object chartView, and display the chart in the chartView.
The setChart(QChart) function in QChartView is used.

(2) The series used to display data on the chart is called a series. Here, the polyline series QLineSeries is used to create two series series0 and series1 of the QLineSeries type, and the series are added to the chart. QChart uses the addSeries(QLineSeries) function.

(3) The sequence stores the data for display, so it is necessary to add the coordinate data of the plane data points for the two sequences. In the program, the sine function and the cosine function are used to generate data as sequence data. QLineSeries uses the append() function.

(4) The chart also needs coordinate axes, create two coordinate axis objects axisX and axisY of type QValueAxis, and then use QChart's setAxisX() and setAxisY() functions to set the x-axis and y-axis for the two sequences respectively.

A legend (Legend) will be automatically generated after the chart is created, and the legend corresponds to the series.
insert image description here
The main components of the chart : QChartView is the view component of QChart, and a chart drawn by QChart generally includes sequence, axis, legend, chart title and other parts.

Guess you like

Origin blog.csdn.net/qq_35412059/article/details/130513108