Set InfLineLabel on horizontal infinite line adjacent to y axis.

22 views
Skip to first unread message

JJ

unread,
Oct 28, 2024, 6:08:04 AM10/28/24
to pyqtgraph
In the code below, I can't get the label to hug the y axis when the graph is resized. If the graph is resized smaller/larger, the label is truncated or additional space appears between the y axis and the label. Any ideas on how to position the label adjacent to the y axis for all graph sizes?

    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_())

Patrick

unread,
Oct 28, 2024, 7:40:00 PM10/28/24
to pyqtgraph
Hi JJ,

Try changing the initialisation parameters of the label to
h_line.label = pg.InfLineLabel(h_line, text=f"y = {h_line.value():.2f}", position=0.00, anchors=[(-0.1, 0), (-0.1, 1)], color='r', fill=(255, 255, 255, 255))

The "position" parameter is relative so needs to be zero so it doesn't expand, but the "anchors" parameter is what gives the fixed offset so the label doesn't get clipped by the y-axis.

Patrick
Reply all
Reply to author
Forward
0 new messages