曦远 (DealiAxy)一份私人的文字刊物

StarBlog
返回文章列表折页手记阅读全文
PyQt

Essential Data Analysis Skills! Learn How to Draw Beautiful Charts in PyQt in 3 Minutes

Let's first look at the effect we want to achieve: This is a display of machine learning-based data analysis results. You can see that the elements include axis labels, two line plots, and a legend. To draw charts in PyQt, we use the pyqtgraph plotting library. It is implemented entirely in Python, integrates perfectly with PyQt programs, and has many advantages: It has a rich variety of chart types; It can quickly update plotting data in real time; It supports interactive operations; Multiple annotation features; Next, let's get to the main topic and start using pyqtgraph to implement our

曦远 (DealiAxy)约 22 分钟
目录10 个章节

Let's first look at the effect we want to achieve:

This is a display of machine learning-based data analysis results. You can see that the elements include axis labels, two line plots, and a legend.

To draw charts in PyQt, we use the pyqtgraph plotting library. It is implemented entirely in Python, integrates perfectly with PyQt programs, and has many advantages:

  • It has a rich variety of chart types;
  • It can quickly update plotting data in real time;
  • It supports interactive operations;
  • Multiple annotation features;

Next, let's get to the main topic and start using pyqtgraph to create the chart we want.

Installation

Installing PyQtGraph is very simple; you can install it directly with pip:

pip install pyqtgraph

PyQtGraph comes with a rich examples module. Enter the following in the command line:

python -m pyqtgraph.examples

This will launch the official demo collection, with the following effect:

It's recommended to look at the effects first, then copy the code of any demos you need into an IDE like PyCharm for editing. The fonts in this software are really ugly—looking at them directly will make you go blind.

Integrating pyqtgraph Charts into PyQt

In PyQtGraph, there are several ways to draw charts:

  • pyqtgraph.plot(): Create a new plot window to display data;
  • PlotWidget.plot(): Add a new set of data to an existing plot widget;
  • PlotItem.plot(): Add a new set of data to an existing plot widget;
  • GraphicsLayout.addPlot(): Add a new plot to a graphics layer;

Based on these plotting methods in PyQtGraph, in PyQt we can display charts in a window widget, or display them in a new window.

The method I use is embedding it into a QGraphicsView component via the Promote To ... feature.

The steps are as follows:

  • In Designer, create a QGraphicsView widget (“Graphics View” under the “Display Widgets” category).
  • Right-click the QGraphicsView and select “Promote To...”.
  • Under “Promoted calss name”, enter the class name you want to use (“PlotWidget”, “GraphicsLayoutWidget”, etc.). Here I chose PlotWidget
  • Under “Header file”, enter “pyqtgraph”.
  • Click “Add”, then click “Promote”.

For more information on promoting widgets, please refer to the Designer documentation. The “VideoSpeedTest” and “ScatterPlotSpeedTest” examples both demonstrate how to use pyui4 or pyside-uic to compile .ui files into .py modules. The “designerExample” example demonstrates dynamically generating a Python class from a .ui file (without needing pyuic4 / pyside-uic).

Then perform a ui2py conversion on the generated ui file. The ui2py operation is simple: run pyuic5.bat in the PyQt installation directory, for example:

pyuic5.bat -o target.py from.ui

After that, you can use this QGraphicsView control as a plotWidget.

Start Drawing

Now back to the effect we wanted to achieve at the beginning. We need two line plots with the same X-axis coordinates, so we need two sets of y coordinates. The coordinate data used in this example is as follows:

x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
     56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80]
b = [9.8, 5.5, 4.5, 4.4, 4.4, 4.1, 4.1, 2.10, 2.10, 2.54, 2.59, 2.66, 3.30, 2.33, 2.23, 2.68, 2.33, 2.67, 2.90, 2.21, 2.56, 2.45, 1.23, 2.45, 2.67,
     2.3, 2.87, 2.65, 1.05, 1.05, 1.05, 1.86, 1.32, 1.34, 2.45, 2.46, 1.11, 1.35, 1.21, 0.00, 0.47, 0.49, 0.50, 0.57, 0.98, 1.21,
     1.35, 1.32, 1.30, 0.46, 0.35, 0.40, 1.41, 0.21, -0.58, -0.90, 0.35, -0.21, -0.30, 0.31, 0.94, 0.15, -0.60, -0.34, 0.56, 0.67, 1.95, 0.45, 1.65, 1.78, 1.34, 1.41, 1.03, 1.05, 0.87, 0.98, 1.25, 0.78, 0.91, 1.42, 1.20]
y = [9.8, 5.5, 4.2, 3.0, 2.8, 3.1, 3.19, 2.94, 2.97, 2.70, 2.45, 3.56, 2.20, 2.34, 2.00, 2.19, 1.73, 1.54, 1.61, 1.60, 1.60, 1.60, 1.60, 1.64, 1.30, 1.30, 1.30, 1.08, 1.21, 1.15, 0.76, 1.21, 1.21, 1.21, 1.21, 0.81, 0.81,
     0.81, 0.81, 0.54, 0.59, 0.50, 1.21, 0.83, 1.00, 0.50, 0.50, 0.50, 0.50, 0.30, 0.30, 0.34, 0.24, 0.24,
     0.24, 0.41, 0.41, 0.56, 0.56, 0.56, 0.56, 0.28, 0.76, 0.53, 0.43, 0.65, 0.50, 0.67, 0.33, 0.40, 0.45, 0.72, 0.68, 0.64, 0.60, 0.60, 0.33, 0.35, 0.51, 0.51, 0.58]

With the coordinates, we can try drawing. Write the following code in the Python file generated by the ui2py step:

# 把graphicsView赋值给plotWidget变量
# 其实这一步可以省略的,不过我们为了可读性写了这一步
plotWidget = self.graphicsView

# 简单的调用画图功能
plotWidget.plot(dataset.x, dataset.y)
plotWidget.plot(dataset.x, dataset.b)

The effect is as follows: You can see that the two line plots have been drawn, but the background is black, the two lines are not distinguished by color, the axes have no labels, and there is no legend... Don't worry, we'll take it step by step.

Set Background Color

Add this line to the previous code:

# w 表示 white 白色
plotWidget.setBackground('w')

The effect is obvious—the background has become white.

But this is not enough. Each line needs a different color to distinguish them. Let's continue.

Set Line Color

Change the previous code to:

plotWidget.setBackground('w')

# 增加了 pen 参数
plotWidget.plot(dataset.x, dataset.y, pen=(1, 2))
plotWidget.plot(dataset.x, dataset.b, pen=(2, 2))

Look at the effect—you can see that the line colors have changed.

So what do the parameters after pen mean? According to the documentation, the 2 in (1,2) means there are 2 lines, and the system will automatically create two different colors. The 1 means this is the first line, using the first color~ If you have more lines, just change the latter number to the number of lines~

If you set pen to None, it won't draw lines, but will draw points instead.

Set Axis Labels

On top of the previous code, add:

# 设置坐标坐标轴标签
plotWidget.setLabel('left', 'LOSS')
# 设置底部坐标轴标签
plotWidget.setLabel('bottom', 'epoch')

nice! The labels are showing.

Next is the last step: setting the legend~

Set Legend

According to the documentation, setting the legend is very simple—just specify a name parameter when drawing the lines. The code is as follows:

# 先添加图例,不然不会显示
plotWidget.addLegend()
plotWidget.plot(dataset.x, dataset.y, pen=(1, 2), name='训练集')
plotWidget.plot(dataset.x, dataset.b, pen=(2, 2), name='测试集')

Look at the effect—we're finally done! The legend is there too~

But compared to our original chart, it seems we're still missing grid lines. This is also very simple—just set a property:

plotWidget.showGrid(x=True, y=True)

Complete Code

Here is the complete code for this example:

plotWidget.addLegend()
plotWidget.setBackground('w')
plotWidget.plot(dataset.x, dataset.y, pen=(1, 2), name='训练集')
plotWidget.plot(dataset.x, dataset.b, pen=(2, 2), name='测试集')
plotWidget.setLabel('left', 'LOSS')
plotWidget.setLabel('bottom', 'epoch')
plotWidget.showGrid(x=True, y=True)

You can modify and practice according to your own needs~

References

If you want to learn more about pyqtgraph operations, you can refer to the following documents. It's highly recommended to read the official documentation and demos first—they're very comprehensive!

Official documentation of the pyqtgraph plotting library: http://www.pyqtgraph.org/

For those who don't want to read the English documentation, you can check out the community-translated Chinese documentation:

Welcome to Connect

I've compiled a series of technical articles and materials. Reply with linux, flutter, c#, netcore, android, java, python, etc. in the backend of the WeChat official account 「程序设计实验室」 to get related technical articles and materials. If you have any questions, you can also leave a message in the official account backend~

_EOF_

Essential Data Analysis Skills! Learn How to Draw Beautiful Charts in PyQt in 3 Minutes

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

PyQt5开发实践(一、准备篇)

前言 近一年来我开发了不少PyQt小项目,因为之前没用过使用C++语言的Qt,所以可以算是从零基础开始边学边做的,这个过程中再一次体会到国内技术社区的匮乏…… 国内关于PyQt的资料说少不少,说多也不多,主要是比较零散,也没什么比较好用的系统的学习资料… 所以这个PyQt,全靠看文档和国外社区,还有一个最重要的:自己摸索…… 开发环境搭建 本文的开发环境搭建一部分是从书里学来的,一部分是实践中总

2021-12-18 · PyQt · 约 1 分钟

并行化优化KD树算法:使用C#实现高效的最近邻搜索

本文介绍了如何使用并行计算技术优化 KD 树算法,并使用 C# 编程语言实现了高效的最近邻搜索。首先,我们简要介绍了 KD 树的原理和构建过程,然后详细讨论了如何利用并行计算库在多个 CPU 核心上并行构建 KD 树,从而加速搜索过程。通过实验验证,我们证明了并行化优化能够显著提高 KD 树的构建速度和搜索效率,为大规模数据集下的最近邻搜索问题提供了一种高效的解决方案。

2024-03-10 · C# · 约 1 分钟

Asp-Net-Core开发笔记:快速在已有项目中引入EFCore

很多项目一开始选型的时候没有选择EFCore,不过EFCore确实好用,也许由于种种原因后面还是需要用到,这时候引入EFCore也很方便。 本文以 StarBlog 为例,StarBlog 目前使用的 ORM 是 FreeSQL ,引入 EFCore 对我来说最大的好处是支持多个数据库,如果是 FreeSQL 的话,服务注册的时候是单例模式,只能连接一个数据库,如果需要使用 FreeSQL 同时

2023-10-08 · Asp-Net-Core开发笔记 · 约 1 分钟

特朗普真得新冠了?

美国当地时间10月1日,懂王发推说中招新冠了… 然后国内媒体集体沸腾,微博热搜都直接安排上了 这就赶在我们国庆节一起庆祝了呗~ 不过吃瓜的同时,作为键政小能手,我们不能盲目跟风,得理性分析一波:马上就到美国大选了,按理说这时候再难也要坚持过去啊,不然民众会说「你个新冠病人跟人凑什么热闹来竞选总统啊,赶紧回家养病」,但这时懂王突然高调宣布感染,要干哈啊?这时候不阴谋论一下都对不起这些年逛知乎政治历史

2022-11-07 · 2020 · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…