TextItem maintain constant position while scaling

1,029 views
Skip to first unread message

wot

unread,
Jun 24, 2017, 6:40:50 PM6/24/17
to pyqtgraph
I would like a TextItem that maintains a constant position on the graph while scaling, essentially the same functionality as legend only a TextItem. Cannot figure out how to do this. Any suggestions welcome.

wot

unread,
Jun 25, 2017, 7:17:42 PM6/25/17
to pyqtgraph
import pyqtgraph as pg 
from PyQt4 import QtGui 
import numpy as np 
import sys 
def main(): 
    app = QtGui.QApplication(sys.argv) 
    widg = QtGui.QWidget() 
    widg.move(100, 100) 
    pg.setConfigOption('background', 'w')
    pg.setConfigOption('foreground', 'k') 

    pgWidg = pg.GraphicsLayoutWidget()   
    pgWidg.resize(750, 250)  

    graph1 = pgWidg.addPlot(row=1, col=1) 
    graph2 = pgWidg.addPlot(row=1, col=2)
    curve1 = graph1.plot(y=np.sin(np.linspace(1, 21, 1000)), pen='k') 
    curve2 = graph2.plot(y=np.sin(np.linspace(1, 21, 1000)), pen='k') 

    graph1.addItem(curve1) 
    graph2.addItem(curve2) 
    graph1.setMouseEnabled(x=False, y=True)
    graph2.setMouseEnabled(x=False, y=True)

    graph1Text = pg.TextItem(text = 'A1', color=(0, 0, 0))
    graph1.addItem(graph1Text)
    graph1Text.setPos(150, 1)

    legend = graph2.addLegend()
    style = pg.PlotDataItem(pen='w')
    legend.addItem(style, 'A2')

    grid = QtGui.QGridLayout() 
    grid.addWidget(pgWidg, 0,0)          
    widg.setLayout(grid) 
    widg.show() 
    sys.exit(app.exec_()) 

if __name__ == '__main__':  
    main()


This example code illustrates the problem. On the lefthand graph, scaling the y-axis causes the text to move whereas on the righthand graph the legend stays in a constant position as you scale. I would like the position of the textItem to be defined like the legend position, in a constant position relative to the graph window. Alternatively if someone knows how to change the format of the legend and update the text that would also work, but from my reading of the documentation this is not possible.

Jeremy Webster

unread,
Jul 11, 2017, 11:04:18 AM7/11/17
to pyqtgraph
I would like this as well, has a solution been found yet? 

Sebastian Höfer

unread,
Jul 11, 2017, 11:44:31 AM7/11/17
to pyqtgraph
Hi,

just a small change in your code does the trick:

    ...

    graph1Text = pg.TextItem(text = 'A1', color=(0, 0, 0))
    # graph1.addItem(graph1Text)
    graph1_vb = graph1.getViewBox()
    graph1Text.setParentItem(graph1_vb)
    graph1Text.setPos(150, 1)
    ...

You can look it up in PlotItem.py in the function addLegend(...).

But if it's just something like a headline or describing text I would recomment to use the GraphicsLayout to put a labelItem above or below your plot.

Cheers,
Sebastian

Reply all
Reply to author
Forward
0 new messages