You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PyQt6的pyqtgraph绘图中添加垂直蓝红渐变背景?

如何在PyQt6+pyqtgraph中为绘图添加垂直渐变背景

虽然pyqtgraph没有直接提供渐变背景的API,但可以借助Qt的原生绘图能力实现这个需求。核心思路是创建自定义图形对象,绘制垂直渐变并添加到绘图的背景层。

实现步骤

  • 定义继承自pg.GraphicsObject的渐变背景类,重写paint和boundingRect方法
  • 在paint方法中用QLinearGradient创建从蓝色到红色的垂直渐变
  • 将自定义背景对象添加到目标PlotItem的背景层,设置层级确保在最底层

修改后的完整代码

import pyqtgraph as pg
from PyQt6.QtWidgets import QApplication
from PyQt6.QtGui import QLinearGradient, QColor, QBrush
from PyQt6.QtCore import Qt

class GradientBackground(pg.GraphicsObject):
    def __init__(self, plot_item):
        super().__init__()
        self.plot_item = plot_item
        # 绑定视图变化信号,确保背景随视图缩放/平移自动适配
        self.plot_item.sigRangeChanged.connect(self.update_bounds)
        self.bounds = self.plot_item.viewRange()
        self.setZValue(-10)  # 设为低层级,保证在曲线下方

    def boundingRect(self):
        x_min, x_max = self.bounds[0]
        y_min, y_max = self.bounds[1]
        return pg.QtCore.QRectF(x_min, y_min, x_max - x_min, y_max - y_min)

    def paint(self, painter, option, widget=None):
        # 创建垂直渐变:顶部蓝色 -> 底部红色,带透明度避免遮挡曲线
        gradient = QLinearGradient(0, self.bounds[1][0], 0, self.bounds[1][1])
        gradient.setColorAt(0, QColor(0, 0, 255, 50))
        gradient.setColorAt(1, QColor(255, 0, 0, 50))
        painter.setBrush(QBrush(gradient))
        painter.setPen(Qt.NoPen)
        painter.drawRect(self.boundingRect())

    def update_bounds(self):
        self.bounds = self.plot_item.viewRange()
        self.prepareGeometryChange()

# 创建应用
app = QApplication([])

# 主窗口与双绘图区
win = pg.GraphicsLayoutWidget(title="Dual Plots Example", size=(800, 400))

# 左侧绘图区
plot1 = win.addPlot(row=0, col=0, title="Signal 1")
plot1.plot([1, 2, 3, 4], [1, 3, 2, 4], pen='b')
# 添加渐变背景
bg1 = GradientBackground(plot1)
plot1.addItem(bg1)

# 右侧绘图区
plot2 = win.addPlot(row=0, col=1, title="Signal 2")
plot2.plot([1, 2, 3, 4], [4, 2, 3, 1], pen='r')
# 添加渐变背景
bg2 = GradientBackground(plot2)
plot2.addItem(bg2)

# 显示窗口
win.show()
app.exec()

关键细节说明

  • 渐变的起始/结束点对应绘图区的y轴范围,实现严格垂直方向的颜色过渡
  • 绑定sigRangeChanged信号,解决视图缩放或平移时背景错位的问题
  • 调整颜色的透明度参数(最后一位数值),平衡背景效果与曲线可读性

内容的提问来源于stack exchange,提问作者Nick Skywalker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 15:52:37