How to show matplotlib.pyplot in qt widget? - python

I want to show the pyplot image in widget (QWidget) that I put in a gui designed in QtDesigner:
When I push the Çiz button I want to show the image that I can create in python with that code:
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 2)
f = np.poly1d(z)
x_fit = np.linspace(min(x), max(x), 10000)
y_fit = [f(_x) for _x in x_fit]
plt.plot(x, y)
plt.plot(x_fit, y_fit)
plt.show()
EDIT
I made some changes according to the answer but I have new problems.
After I promote it:
I rearrange my code below:
# calculate polynomial and r
self.x_fit = np.linspace(min(self.itemX), max(self.itemY), 10000)
self.y_fit = [f(_x) for _x in self.x_fit]
self._dlg.plotwidget.plot(self.itemX, self.itemY)
self._dlg.plotwidget.plot(self.x_fit, self.y_fit)
self.itemX is x values in a list.
self.itemY is y values in a list.
self._dlg is the MainWindow that you see.
When I try to open that window I get this error message:

I just tested the code below works for me:
import sys
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui, uic
uifilename = 'test.ui'
form_class = uic.loadUiType(uifilename)[0] #dirty reading of the ui file. better to convert it to a '.py'
class MyWindowClass(QtGui.QMainWindow, form_class):
def __init__(self):
QtGui.QMainWindow.__init__(self)
self.setupUi(self)
self.onInit()
def onInit(self):
#usually a lot of connections here
self.x_fit = np.linspace(1,10000, 10000)
self.y_fit = [f(_x) for _x in self.x_fit]
self.plotwidget.plot(self.x_fit,self.y_fit,symbol='o',pen=None)
self.plotwidget.setLabel('left',text='toto',units='')
self.plotwidget.setLabel('top',text='tata',units='')
def f(x):
return x**2+1
if __name__ == '__main__':
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
app = QtGui.QApplication([])
pg.setConfigOption('background', 'w')
win = MyWindowClass()
win.show()
app.exec_()
with this test.ui : https://github.com/steph2016/profiles/blob/master/test.ui.
Note the plotwidget is encapsulated inside a layout. I thought it works with just the Main Window, but I'm not sure anymore...

Sorry I don't exactly answer the question but I don't use matplotlib.pyplot with pyqt. I recommend using pyqtgraph (http://pyqtgraph.org), which is quite convenient and powerful. With Qt Designer:
you just insert a 'graphics view' in your GUI
you right-click on it and promote it to "plotwidget" using pyqtgraph. I guess the english tab is something like this: base class 'QGraphicsView'; promoted class 'PlotWidget'; header file 'pyqtgraph', then 'add', then 'promote'
then you can make plotwidget.plot(x,y,...), plotwidget.clear(), and co. It will plot everything inside the plotwidget with a bunch of interacting possibilities

Related

How to reset/ start a new polygon with embeded matplotlib in pyqt

I am trying to create a polygon selector in my PySide2 application. Selector is working fine, but then I want to add functionality to reset/start new polygon when escape button is pressed. Something similar to this PolygonSelector example, when escape is pressed.
https://matplotlib.org/stable/gallery/widgets/polygon_selector_demo.html
I tried method .clear() but it does not seems to work for me.
import sys
import numpy as np
from PySide2 import QtWidgets, QtGui
from matplotlib.backends.backend_qtagg import (
FigureCanvas, NavigationToolbar2QT as NavigationToolbar)
from matplotlib.figure import Figure
from matplotlib.widgets import PolygonSelector
class ApplicationWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self._main = QtWidgets.QWidget()
self.setCentralWidget(self._main)
shortcut_clear_selection = QtWidgets.QShortcut(QtGui.QKeySequence("Escape"), self._main)
shortcut_clear_selection.activated.connect(self.callback_clear_selection)
layout = QtWidgets.QVBoxLayout(self._main)
static_canvas = FigureCanvas(Figure(figsize=(5, 3)))
layout.addWidget(NavigationToolbar(static_canvas, self))
layout.addWidget(static_canvas)
ax = static_canvas.figure.subplots()
t = np.linspace(0, 10, 501)
ax.plot(t, np.tan(t), ".")
self.poly = PolygonSelector(ax, self.onselect)
def onselect(self, verts):
pass
def callback_clear_selection(self):
# HERE should be the reset part
self.poly.clear()
if __name__ == "__main__":
qapp = QtWidgets.QApplication(sys.argv)
app = ApplicationWindow()
app.show()
app.activateWindow()
app.raise_()
qapp.exec_()
Problem is, that ESC key release event is not handled by PolygonSelector but Your callback. Therefore, to clear polygon and restart creation of polygon You have to clear polygon data and show selector again. clear method was just hiding selector, but polygon data stayed unchanged.
Change Your callback code into this:
def callback_clear_selection(self):
# HERE should be the reset
self.poly._xs, self.poly._ys = [0], [0]
self.poly._selection_completed = False
self.poly.set_visible(True)
Now, when You press ESC, polygon should be removed and You can start selection of new one.

Convert pixel/scene coordinates (from MouseClickEvent) to plot coordinates

I have a GraphicsLayoutWidget to which I added a PlotItem. I'm interested in clicking somewhere in the graph (not on a curve or item) and getting the clicked point in graph coordinates. Therefore I connected the signal sigMouseClicked to a custom method something like this:
...
self.graphics_view = pg.GraphicsLayoutWidget()
self.graphics_view.scene().sigMouseClicked.connect(_on_mouse_clicked)
def _on_mouse_clicked(event):
print(f'pos: {event.pos()} scenePos: {event.scenePos()})
...
While this gives me coordinates that look like e.g. Point (697.000000, 882.000000), I struggle to convert them to coordinates in "axes" coordinates of the graph (e.g. (0.3, 0.5) with axes in the range [0.1]). I tried many mapTo/From* methods without success.
Is there any way to archive this with PyQtGraph?
You have to use the viewbox of the plotitem:
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.graphics_view = pg.GraphicsLayoutWidget()
self.setCentralWidget(self.graphics_view)
self.plot_item = self.graphics_view.addPlot()
curve = self.plot_item.plot()
curve.setData([0, 0, 1, 1, 2, 2, 3, 3])
self.graphics_view.scene().sigMouseClicked.connect(self._on_mouse_clicked)
def _on_mouse_clicked(self, event):
p = self.plot_item.vb.mapSceneToView(event.scenePos())
print(f"x: {p.x()}, y: {p.y()}")
def main():
app = QtGui.QApplication([])
w = MainWindow()
w.show()
app.exec_()
if __name__ == "__main__":
main()

Put a Matplotlib plot as a QGraphicsItem/into a QGraphicsView

So I have a very basic plot layout described below (with x and y values changed for brevity):
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import numpy as np
figure = Figure()
axes = figure.gca()
axes.set_title(‘My Plot’)
x=np.linspace(1,10)
y=np.linspace(1,10)
y1=np.linspace(11,20)
axes.plot(x,y,’-k’,label=‘first one’)
axes.plot(x,y1,’-b’,label=‘second one’)
axes.legend()
axes.grid(True)
And I have designed a GUI in QT designer that has a GraphicsView (named graphicsView_Plot) that I would like to put this graph into and I would like to know how I would go about putting this graph into the GraphicsView. Barring starting over and using the QT based graphing ability I don’t really know how (if possible) to put a matplotlib plot into this graphics view. I know it would be a super simple thing if I can convert it into a QGraphicsItem as well, so either directly putting it into the GraphicsView or converting it to a QGraphicsItem would work for me.
You have to use a canvas that is a QWidget that renders the matplotlib instructions, and then add it to the scene using addWidget() method (or through a QGraphicsProxyWidget):
import sys
from PyQt5 import QtWidgets
from matplotlib.figure import Figure
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import numpy as np
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
scene = QtWidgets.QGraphicsScene()
view = QtWidgets.QGraphicsView(scene)
figure = Figure()
axes = figure.gca()
axes.set_title("My Plot")
x = np.linspace(1, 10)
y = np.linspace(1, 10)
y1 = np.linspace(11, 20)
axes.plot(x, y, "-k", label="first one")
axes.plot(x, y1, "-b", label="second one")
axes.legend()
axes.grid(True)
canvas = FigureCanvas(figure)
proxy_widget = scene.addWidget(canvas)
# or
# proxy_widget = QtWidgets.QGraphicsProxyWidget()
# proxy_widget.setWidget(canvas)
# scene.addItem(proxy_widget)
view.resize(640, 480)
view.show()
sys.exit(app.exec_())

turning grid on with AxisItem in pyqtgraph causes axis scaling to break

I am having trouble with AxisItem. As soon as I turn on both the x and y grid, the x-axis is no longer able to scale in and out with the zoom/pan function. Any ideas?
from PyQt4 import QtCore, QtGui
from pyqtgraph import Point
import pyqtgraph as pg
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
class plotClass(QtGui.QMainWindow):
def setupUi(self, MainWindow):
self.centralwidget = QtGui.QWidget(MainWindow)
MainWindow.resize(1900, 1000)
self.viewbox = pg.GraphicsView(MainWindow, useOpenGL=None, background='default')
self.viewbox.setGeometry(QtCore.QRect(0, 0, 1600, 1000))
self.layout = pg.GraphicsLayout()
self.viewbox.setCentralWidget(self.layout)
self.viewbox.show()
self.view = self.layout.addViewBox()
self.axis1 = pg.AxisItem('bottom', linkView=self.view, parent=self.layout)
self.axis2 = pg.AxisItem('right', linkView=self.view, parent=self.layout)
self.axis1.setGrid(255)
self.axis2.setGrid(255)
self.layout.addItem(self.axis1, row=1, col=0)
self.layout.addItem(self.axis2, row=0, col=1)
if __name__== "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = plotClass()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Looking at your last comment, consider this option:
The pyqtgraph examples folder contains a "GraphItem.py" example which adds and displays a GraphItem object to a window via a ViewBox only. They don't use a grid however, so if you want to use a grid with a GraphItem, just add a PlotItem first (which has an associated ViewBox already... and you guessed it,...AxisItems for a grid!),... then get the ViewBox to add your GraphItems. The modified GraphItem.py would look like this (with the accompanying showGrid):
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
# Enable antialiasing for prettier plots
pg.setConfigOptions(antialias=True)
w = pg.GraphicsWindow()
w.setWindowTitle('pyqtgraph example: GraphItem')
### comment out their add of the viewbox
### since the PlotItem we're adding will have it's
### own ViewBox
#v = w.addViewBox()
pItem1 = w.addPlot() # this is our new PlotItem
v = pItem1.getViewBox() # get the PlotItem's ViewBox
v.setAspectLocked() # same as before
g = pg.GraphItem() # same as before
v.addItem(g) # same as before
pItem1.showGrid(x=True,y=True) # now we can turn on the grid
### remaining code is the same as their example
## Define positions of nodes
pos = np.array([
[0,0],
[10,0],
[0,10],
[10,10],
[5,5],
[15,5]
])
## Define the set of connections in the graph
adj = np.array([
[0,1],
[1,3],
[3,2],
[2,0],
[1,5],
[3,5],
])
## Define the symbol to use for each node (this is optional)
symbols = ['o','o','o','o','t','+']
## Define the line style for each connection (this is optional)
lines = np.array([
(255,0,0,255,1),
(255,0,255,255,2),
(255,0,255,255,3),
(255,255,0,255,2),
(255,0,0,255,1),
(255,255,255,255,4),
], dtype=[('red',np.ubyte),('green',np.ubyte),('blue',np.ubyte),('alpha',np.ubyte),('width',float)])
## Update the graph
g.setData(pos=pos, adj=adj, pen=lines, size=1, symbol=symbols, pxMode=False)
## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
QtGui.QApplication.instance().exec_()
I tested this and the scroll/zooming still worked after enabling the grid, so still not sure why doing it the other way DOESN'T work, but sometimes finding another way is the best answer :)

Python: pyQt, Qthread and matplotlib: subplots crash at the second call

I am trying to draw graphs with the result of a thread using matplotlib. First I launch the thread using a pyqt button, all is ok. But the second time I press the button, subplots crash because I suppose tuples can't be modified. This is my simplfied code that you can try and see by yourself:
from PyQt4 import QtGui, QtCore
import matplotlib.pyplot as plt
import numpy as np
from PyQt4.Qt import *
import sys
class thread(QThread):
def __init__(self, parent=None):
QThread.__init__(self, parent)
def __del__(self):
self.wait()
def render(self):
self.start()
def run(self):
data = [(1, 10), (3, 100), (4, 1000), (5, 100000)]
data_in_array = np.array(data)
transposed = data_in_array.T
x, y = transposed
fig, ax = plt.subplots(1,1)
ax.plot(x, y, 'ro')
ax.plot(x, y, 'b-')
plt.show()
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
self.button = QtGui.QPushButton('Test', self)
self.button.clicked.connect(self.handleButton)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.button)
self.thread=thread()
def handleButton(self):
self.thread.render()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
Please, how can I solve it to avoid crash and uses several times my button?
Thanks
This is not the right way to mix your Qt application and Matplotlib (which uses Qt in its backend).
See https://matplotlib.org/gallery/user_interfaces/embedding_in_qt_sgskip.html for a better explanation than I can provide.
I got the same problem, was searching solution.
By adding these 3 lines solved the issue. Please add these 3 lines before importing pyplot
import matplotlib as mpl
mpl.rcParams['backend'] = "qt4agg"
mpl.rcParams['backend.qt4'] = "PySide"

Categories