返回文章列表文章索引阅读全文
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 分钟

Asp-Net-Core学习笔记:5.构建和部署

从上次开始学习Asp.Net Core以来,一直都是玩一玩,还没有什么机会用来实战,最近公司有个新的小项目,于是我用Asp.Net Core来尝尝新,结果也是非常OK,熟悉之后开发效率感觉和Django基本没差。 那么进入正题,本文简单说说Asp.Net Core应用的构建和部署。 构建 构建是使用build命令,不过一般我们都用vs或者rider之类的IDE,应该比较少会用到这个命令: dotn

2022-02-16 · Asp-Net-Core学习笔记 · 约 1 分钟

Windows设置Pageant开机自动启动并且加载秘钥

场景 用Linux的时候ssh和git这些很方便,因为只要一次ssh-add就可以一劳永逸,以后需要认证的时候ssh-agent会帮我们搞定,不需要输入秘钥的密码。 其实Windows也可以实现这种生产力解放,就是用putty附带的工具里的Pageant。 Pageant主要负责和服务器端进行身份验证,但是每次在启动Pageant后都需要手动的加载秘钥文件,本文就是要介绍让Pageant开机自动加

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

讨论

共 0 条

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

加载评论中…