Search code examples
pythonpyqtgraph

pyqtgraph How to add multiple plots to one ax


I want to open a window with pyqtgraph alone, without using pyqt.

I want to create two or more axes in one window through pyqtgraph, and draw two lines in one ax. What should I do?

The following code creates multiple windows.

import pandas as pd
import pyqtgraph as pg

a = [
    {'a': 5, 'b': 10, 'c': 5},
    {'a': 4, 'b': 0.5, 'c': 1},
    {'a': 3.5, 'b': 15, 'c': 9},
    {'a': 2.1, 'b': 5, 'c': 8},
    {'a': 0.1, 'b': 1, 'c': 5},
]

df = pd.DataFrame(a)
pg.plot(df['a'].values)
pg.plot(df['b'].values)
pg.exec()

The following code does not create a window.

import pandas as pd
import pyqtgraph as pg

a = [
    {'a': 5, 'b': 10, 'c': 5},
    {'a': 4, 'b': 0.5, 'c': 1},
    {'a': 3.5, 'b': 15, 'c': 9},
    {'a': 2.1, 'b': 5, 'c': 8},
    {'a': 0.1, 'b': 1, 'c': 5},
]

df = pd.DataFrame(a)
widget = pg.MultiPlotWidget()
widget.addItem(pg.PlotWidget(df['a'].values))
widget.addItem(pg.PlotWidget(df['b'].values))
pg.exec()

Solution

  • I think this is what you are looking for:

    import pandas as pd
    import pyqtgraph as pg
    
    a = [
        {'a': 5, 'b': 10, 'c': 5},
        {'a': 4, 'b': 0.5, 'c': 1},
        {'a': 3.5, 'b': 15, 'c': 9},
        {'a': 2.1, 'b': 5, 'c': 8},
        {'a': 0.1, 'b': 1, 'c': 5},
    ]
    df = pd.DataFrame(a)
    
    app = pg.mkQApp()
    fig_widget = pg.GraphicsLayoutWidget()
    
    p1 = pg.PlotItem()
    p2 = pg.PlotItem()
    
    fig_widget.addItem(p1, 0, 0)
    fig_widget.addItem(p2, 0, 1)
    
    curve_1 = pg.PlotDataItem(df["a"].values)
    curve_2 = pg.PlotDataItem(df["b"].values)
    curve_3 = pg.PlotDataItem(df["c"].values)
    
    p1.addItem(curve_1)
    p1.addItem(curve_2)
    p2.addItem(curve_3)
    
    fig_widget.show()
    
    app.exec()
    

    This method uses a pg.GraphicsLayoutWidget() to which plotItems can be added, which serve as axes, to which PlotDataItems can be added, which serve as lines.