QT-demo:0轴分布图表

news/2024/10/11 3:21:12/

版本:5.9

第一种: 使用 PyQt5 和 Matplotlib 库

安装所需的库:

pip install PyQt5 matplotlib

创建和显示图表:

import sys
import numpy as np
import matplotlib.pyplot as plt
from PyQt5.QtWidgets import QApplication, QMainWindow
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvasclass PlotCanvas(FigureCanvas):def __init__(self, parent=None):fig, self.ax = plt.subplots()super(PlotCanvas, self).__init__(fig)self.setParent(parent)self.plot()def plot(self):# Example datax = np.linspace(0, 10, 1000)y = np.sin(x) * 1000self.ax.fill_between(x, y, where=(y > 0), interpolate=True, color='red', alpha=0.5)self.ax.fill_between(x, y, where=(y <= 0), interpolate=True, color='blue', alpha=0.5)self.ax.axhline(0, color='black', linewidth=0.5)self.ax.set_xlabel('Time')self.ax.set_ylabel('Power (MW)')self.ax.set_title('Power Output')self.draw()class MainWindow(QMainWindow):def __init__(self):super().__init__()self.setWindowTitle("Power Output Graph")self.setGeometry(100, 100, 800, 600)self.canvas = PlotCanvas(self)self.setCentralWidget(self.canvas)app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())

上面的代码创建了一个包含两个区域(红色和蓝色)的图表,表示功率输出为正值或负值。您可以将 xy 数据替换为您的实际数据,并根据需要调整图表的标签和标题。

请运行此代码来查看生成的图表。这个示例假定您使用的是 Python,并且已安装 PyQt5 和 Matplotlib 库。

第二种:使用 Qt5 和 QCustomPlot 库

确保已经安装QCustomPlot 库,如果你还没有安装,可以从 QCustomPlot 官方网站 下载,并将其包含到你的 Qt 项目中。

自取链接:链接:https://pan.baidu.com/s/1CHe1wN5rhQAPd8bcyvlRfQ?pwd=1024 
提取码:1024 

以下是完整demo:

main.cpp:

#include <QApplication>
#include <QMainWindow>
#include "qcustomplot.h"void setupPlot(QCustomPlot *customPlot) {// Create dataQVector<double> x(1001), y(1001); // initialize with entries 0..1000for (int i = 0; i < 1001; ++i) {x[i] = i / 50.0 - 10; // x goes from -10 to 10y[i] = qSin(x[i]) * 1000; // let's plot a sine wave}// Create graph and assign data to it:QCPGraph *graph = customPlot->addGraph();graph->setData(x, y);// Set axis labels:customPlot->xAxis->setLabel("Time");customPlot->yAxis->setLabel("Power (MW)");// Set axis ranges to show the data:customPlot->xAxis->setRange(-10, 10);customPlot->yAxis->setRange(-1500, 1500);// Set fill color:QCPGraph *negativeGraph = customPlot->addGraph();negativeGraph->setData(x, y);negativeGraph->setPen(Qt::NoPen);negativeGraph->setBrush(QBrush(QColor(255, 0, 0, 100))); // Red color for positive valuesQCPGraph *positiveGraph = customPlot->addGraph();positiveGraph->setData(x, y);positiveGraph->setPen(Qt::NoPen);positiveGraph->setBrush(QBrush(QColor(0, 0, 255, 100))); // Blue color for negative valuesfor (int i = 0; i < y.size(); ++i) {if (y[i] > 0) {y[i] = 0;}}negativeGraph->setData(x, y);for (int i = 0; i < y.size(); ++i) {if (y[i] < 0) {y[i] = 0;}}positiveGraph->setData(x, y);customPlot->replot();
}int main(int argc, char *argv[]) {QApplication app(argc, argv);QMainWindow window;QCustomPlot customPlot;setupPlot(&customPlot);window.setCentralWidget(&customPlot);window.resize(800, 600);window.show();return app.exec();
}
  1. 创建一个 qcustomplot.hqcustomplot.cpp 文件,并从 QCustomPlot 官方网站 下载最新版本的 QCustomPlot 代码,然后将其包含在你的项目中。

  2. 在你的项目文件中(例如 CMakeLists.txt*.pro 文件),确保包含 QCustomPlot 的头文件和源文件。例如,在 *.pro 文件中添加以下内容:

    QT += core guigreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsTARGET = your_project_name
    TEMPLATE = appSOURCES += main.cpp \qcustomplot.cppHEADERS += qcustomplot.h
    

  3. 使用 Qt Creator 打开项目并运行它。
  4. 这样你就可以看到一个类似于你提供的图像的绘图了。这个示例代码生成了一个正弦波并将其分成两个区域(红色和蓝色),分别表示功率输出的正值和负值。

运行截图:

如果想把上下都填充颜色,且上下颜色区分。我们需要分别为正值和负值创建两个图层,并为其填充颜色分别设置为红色和蓝色。还需要确保数据正确的分开填充,以便能显示正确的颜色。

#include <QApplication>
#include <QMainWindow>
#include "qcustomplot.h"void setupPlot(QCustomPlot *customPlot) {// Create dataQVector<double> x(1001), y(1001), y_positive(1001), y_negative(1001); // initialize with entries 0..1000for (int i = 0; i < 1001; ++i) {x[i] = i / 50.0 - 10; // x goes from -10 to 10y[i] = qSin(x[i]) * 1000; // let's plot a sine wavey_positive[i] = (y[i] > 0) ? y[i] : 0; // Only positive valuesy_negative[i] = (y[i] < 0) ? y[i] : 0; // Only negative values}// Create positive graph and assign data to it:QCPGraph *positiveGraph = customPlot->addGraph();positiveGraph->setData(x, y_positive);positiveGraph->setPen(Qt::NoPen);positiveGraph->setBrush(QBrush(QColor(0, 0, 255, 100))); // Blue color for positive values// Create negative graph and assign data to it:QCPGraph *negativeGraph = customPlot->addGraph();negativeGraph->setData(x, y_negative);negativeGraph->setPen(Qt::NoPen);negativeGraph->setBrush(QBrush(QColor(255, 0, 0, 100))); // Red color for negative values// Set axis labels:customPlot->xAxis->setLabel("Time");customPlot->yAxis->setLabel("Power (MW)");// Set axis ranges to show the data:customPlot->xAxis->setRange(-10, 10);customPlot->yAxis->setRange(-1500, 1500);customPlot->replot();
}int main(int argc, char *argv[]) {QApplication app(argc, argv);QMainWindow window;QCustomPlot customPlot;setupPlot(&customPlot);window.setCentralWidget(&customPlot);window.resize(800, 600);window.show();return app.exec();
}

分别为正值和负值创建了两个独立的数据集 'y_positive' 和 'y_negative',并将它们添加到两个不同图层中。然后分别设置这些图层的填充颜色。这样既可以保证0轴上方填充为蓝色,下方为红色。

请确保你已经正确地包含了 QCustomPlot 的头文件和源文件,并且在项目文件中添加了对 printsupport 模块的引用:

QT += core gui printsupportgreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsTARGET = chart_test
TEMPLATE = appSOURCES += main.cpp \qcustomplot.cppHEADERS += qcustomplot.h

运行效果:

报错解决:qcustomplot.cpp:15260: error: undefined reference to `_imp___ZN8QPrinterC1ENS_11PrinterModeE' debug/qcustomplot.o: In function `ZN11QCustomPlot7savePdfERK7QStringiiN3QCP9ExportPenES2_S2_': D:\Qt_Projects\My_Demo\build-chart_test-Desktop_Qt_5_15_2_MinGW_32_bit-Debug/../chart_test/qcustomplot.cpp:15260: undefined reference to `_imp___ZN8QPrinterC1ENS_11PrinterModeE'

这个错误通常是由于缺少 Qt 打印模块的链接。为了修复这个问题,需要在项目文件中添加对 Qt 打印支持模块的引用。

QT += printsupport

这个修改确保项目链接了 printsupport 模块,从而解决 QPrinter 的未定义引用问题。


http://www.ppmy.cn/news/1464064.html

相关文章

【Go语言入门学习笔记】Part5.函数

一、前言 这里的还是跟C有区别的&#xff0c;大家熟悉了其他语言后&#xff0c;还得注意一下这里的内容。Go的函数非常灵活。 二、学习代码 package mainimport "fmt"// ZhengXing 类似typedef的方法 type ZhengXing int// 函数名有说法&#xff0c;首字母大写是pu…

探索智能零售的未来商机与运营策略

探索智能零售的未来商机与运营策略 在智能零售的广阔图景中&#xff0c;无人售货机加盟赫然矗立为一股不可小觑的力量&#xff0c;预示着零售业态未来的转型与机遇。其核心优势多维展开&#xff0c;具体阐述如下&#xff1a; 1. **全天候服务**&#xff1a;无人售货机的运行跨…

php反序列化学习(1)

1、php面向对象基本概念 类的定义&#xff1a; 类是定义了一件事物的抽象特征&#xff0c;它将数据的形式以及这些数据上的操作封装住在一起。&#xff08;对象是具有类类型的变量&#xff0c;是对类的实例&#xff09; 构成&#xff1a; 成员变量&#xff08;属性&#xf…

Window在VScode运行C/C++程序

首先说明&#xff1a;不同运行环境&#xff08;Linux/Window&#xff09;下的头文件会有差异&#xff0c;要注意变换&#xff01;生成可执行文件 Window默认生成a.exe&#xff0c;Linux默认生成a.out # C源代码 g test.cpp # C语言源代码 g test.c 或 gcc test.c直接输入a.ex…

Sqoop的安装与测试

这里写目录标题 什么是Sqoop?Sqoop的安装与配置安装测试 什么是Sqoop? Sqoop就是hadoop和mysql的一个中间介质 , 作用就是可以将hadoop中的数据传到mysql中 , 或将mysql中的数据导入到hadoop中 Sqoop的安装与配置 安装 详细代码 //解压安装 [roothadoop soft]# tar -zxv…

【前端之npm镜像地址】

npm镜像地址 淘宝镜像地址华为镜像地址腾讯云镜像地址 淘宝镜像地址 npm config set registry https://registry.npmmirror.com查看镜像设置: npm config get registry 华为镜像地址 npm config set registry https://mirrors.huaweicloud.com/repository/npm/ 腾讯云镜像地…

集合的交集、并集和差集运算

自学python如何成为大佬(目录):https://blog.csdn.net/weixin_67859959/article/details/139049996?spm1001.2014.3001.5501 集合最常用的操作就是进行交集、并集、差集和对称差集运算。进行交集运算时使用“&”符号&#xff0c;进行并集运算时使用“&#xff5c;”符号&…

灵动微单片机洗衣机方案——【软硬件开发支持】

RAMSUN英尚以洗衣机洗涤主驱电机为例&#xff0c;主驱电机和多电机控制首选MM32SPIN0280.灵动微电子能够提供完整的软硬件开发支持&#xff0c;目前方案已经在主流家电厂出货。 洗衣机方案 皮带洗衣机 DD直驱洗衣机 波轮洗衣机 Mini壁挂和桌面洗衣机 洗涤烘干双变频方案 热泵烘…