在pyqtgraph中定位InfLineLabel时出现问题

问题描述 投票:0回答:1

我在 pyqtgraph 中使用如下水平线。如果我将标签的位置设置为 0.05,那么它会以默认的图形大小紧贴 y 轴。但是,如果我调整图表大小,则会出现偏移。将标签位置设置为 0 不起作用,因为标签的一部分会被切断。有没有办法将标签直接放置在 y 轴附近,而不管图形大小如何?

import sys
import numpy as np
from PyQt5.QtWidgets import QApplication
import pyqtgraph as pg

app = QApplication(sys.argv)
win = pg.GraphicsLayoutWidget(show=True, title="y = exp(x) with Movable Line")
plot = win.addPlot(title="y = exp(x) with Movable Line")
x = np.linspace(-2, 2, 1000)
y = np.exp(x)
plot.plot(x, y, pen='b')

# Create a movable infinite horizontal line with a label that updates based on y-position
h_line = pg.InfiniteLine(pos=1.0, angle=0, movable=True)
plot.addItem(h_line)
h_line.label = pg.InfLineLabel(h_line, text=f"y = {h_line.value():.2f}", position=0.05, color='r', fill=(255, 255, 255, 255))

def update_label():
    h_line.label.setText(f"y = {h_line.value():.2f}")

h_line.sigPositionChanged.connect(update_label)
sys.exit(app.exec_())
pyqtgraph
1个回答
0
投票

Pyqtgraph 将

InfiniteLabel
定位到
InfiniteLine
的中心。这就是为什么设置
position = 0
会切掉一半标签。因此,基本上您需要将
label_width / 2
添加到无限标签位置计算中。之后标签应该与 Y 轴很好地对齐。

这是您可以使用的示例代码:

import sys
import numpy as np
from PyQt5.QtWidgets import QApplication
import pyqtgraph as pg


class InfLabel(pg.InfLineLabel):

    def updatePosition(self):
        # update text position to relative view location along line
        self._endpoints = (None, None)
        pt1, pt2 = self.getEndpoints()
        if pt1 is None:
            return
        pt = pt2 * self.orthoPos + pt1 * (1 - self.orthoPos)

        half_label_width = self.mapRectToParent(self.boundingRect()).width() / 2
        pt.setX(pt.x() + half_label_width)

        self.setPos(pt)

        # update anchor to keep text visible as it nears the view box edge
        vr = self.line.viewRect()
        if vr is not None:
            self.setAnchor(self.anchors[0 if vr.center().y() < 0 else 1])


app = QApplication(sys.argv)
win = pg.GraphicsLayoutWidget(show=True, title="y = exp(x) with Movable Line")
plot = win.addPlot(title="y = exp(x) with Movable Line")
x = np.linspace(-2, 2, 1000)
y = np.exp(x)
plot.plot(x, y, pen='b')

# Create a movable infinite horizontal line with a label that updates based on y-position
h_line = pg.InfiniteLine(pos=1.0, angle=0, movable=True)
plot.addItem(h_line)
h_line.label = InfLabel(h_line, text=f"y = {h_line.value():.2f}", position=0, color='r', fill=(255, 255, 255, 255))


def update_label():
    h_line.label.setText(f"y = {h_line.value():.2f}")
    h_line.label.updatePosition()


h_line.sigPositionChanged.connect(update_label)
sys.exit(app.exec_())

© www.soinside.com 2019 - 2024. All rights reserved.