Embedding transparent matplotlib figure canvas in wx - matplotlib

I have a GUI written in wxPython with a matplotlib figure embedded. I want the background color of the figure to be the same as the rest of the (quite large) GUI. Unfortunately the exact color of the GUI is OS-dependent, so it is not enough to set a fixed background color since it will change with the OS. Therefore I tried to use facecolor='none' when creating the matplotlib-figure. However that gave some unexpected problems (see image below): every time you redraw the canvas the label text and tick marks is getting thicker as if the weight of the font is changing. I found this three years old question, which seems to deal with a very similar problem, but it does not have any solution nor comments of what to do. Is this an intended feature of matplotlib/wxpython or just a bug which as not yet been fixed?
Example code to show the problem. I create two FigureCanvases, where the first one has a facecolor='b background, and with it the text is not getting thicker when redrawing the canvas. The second canvas is using facecolor='none', and gives thicker and thicker text for each canvas redraw.
import wx
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
class MyCanvas(wx.Panel):
def __init__(self, parent, col):
wx.Panel.__init__(self, parent, id=-1)
self.fig = Figure(figsize=(1, 1), edgecolor='k', facecolor=col)
self.ax = self.fig.add_subplot(1, 1, 1)
self.ax.set_ylabel('Label')
self.fig.subplots_adjust(left=0.5)
self.canvas = FigureCanvasWxAgg(self, -1, self.fig)
szr_ctr = wx.BoxSizer(wx.VERTICAL)
szr_ctr.Add(self.canvas, 1, wx.ALL | wx.GROW)
self.SetSizerAndFit(szr_ctr)
wx.CallAfter(self.canvas.draw)
class wind(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent)
self.i = 0
figsizer = wx.BoxSizer(wx.HORIZONTAL)
self.canvas1 = MyCanvas(self, col='b')
figsizer.Add(self.canvas1, 1, wx.GROW | wx.ALL)
self.canvas2 = MyCanvas(self, col='none')
figsizer.Add(self.canvas2, 1, wx.GROW | wx.ALL)
button = wx.Button(self, wx.ID_CLOSE, "Press me")
button.Bind(wx.EVT_BUTTON, self.on_button)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(figsizer, 1, wx.ALL | wx.GROW, 10)
sizer.Add(button, 0, wx.ALL, 10)
self.SetSizer(sizer)
self.Layout()
self.Show()
def on_button(self, event):
wx.CallAfter(self.canvas1.canvas.draw)
wx.CallAfter(self.canvas2.canvas.draw)
if __name__ == '__main__':
wxapp = wx.App(redirect=False)
v = wind(None, "Fig")
wxapp.MainLoop()
Figure with blue background works as expected. Figure with none background gets thicker and thicker texts and axes-lines after a few canvas redraws.
Edit
Changing the redraw-function to (below) solves the problem with the canvas not being properly redrawn.
def on_button(self, event):
wx.CallAfter(self.canvas1.canvas.draw)
wx.CallAfter(self.canvas2.canvas.draw)
wx.CallAfter(self.canvas1.Refresh) # <-----------
wx.CallAfter(self.canvas2.Refresh) # <-----------

After fiddling around a bit more, I realised the problem can be solved by using self.canvas_i.Refresh() after self.canvas_i.canvas.draw(). As far as I understand Refresh will mark the canvas as "in need of redrawing", forcing it to be repainted completely. This overpaints any old content and makes it just one iteration old (every new canvas.draw just draws the new thing ontop of the old, slightly placed to the side giving "thicker text").

Related

Matplotlib: Multiple plots with same layout (no automatic layout)

I am trying to make several pie charts that I can then transition between in a presentation. For this, it would be very useful for the automatic layouting to... get out of the way. The problem is that whenever I change a label, the whole plot moves around on the canvas so that it fits perfectly. I'd like the plot to stay centered, so it occupies the same area every time. I have tried adding center=(0,0) to ax.pie(), but to no avail.
Two examples:
Image smaller, left
Image larger, right
Instead of that effect, I'd like the pie chart to be in the middle of the canvas and have the same size in both cases (and I'd then manually make sure that the labels are on canvas by setting large margins).
The code I use to generate these two images is:
import matplotlib.pyplot as plt
import numpy as np
# Draw labels, from
# https://matplotlib.org/3.2.2/gallery/pie_and_polar_charts/pie_and_donut_labels.html#sphx-glr-gallery-pie-and-polar-charts-pie-and-donut-labels-py
def make_labels(ax, wedges, labs):
bbox_props = dict(boxstyle="square,pad=0.3", fc="w", ec="k", lw=0.72)
kw = dict(arrowprops=dict(arrowstyle="-"),
bbox=bbox_props,
zorder=0, va="center")
for i, p in enumerate(wedges):
if p.theta2-p.theta1 < 5:
continue
ang = (p.theta2 - p.theta1) / 2. + p.theta1
y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))
horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
connectionstyle = "angle,angleA=0,angleB={}".format(ang)
kw["arrowprops"].update({"connectionstyle": connectionstyle})
ax.annotate(labs[i], xy=(x, y),
xytext=(1.1*x,1.1*y),
horizontalalignment=horizontalalignment, **kw)
kw=dict(autoscale_on=False, in_layout=False, xmargin=1, ymargin=1)
fig, ax = plt.subplots(figsize=(3, 3), dpi=100, subplot_kw=kw)
wedges, texts = ax.pie(x=[1,2,3], radius=1,
wedgeprops=dict(width=1),
pctdistance=0.7,
startangle=90,
textprops=dict(fontsize=8),
center=(0, 0))
make_labels(ax, wedges, ["long text", "b", "c"])
#make_labels(ax, wedges, ["a", "b", "long text"])
plt.show()
Thanks a lot in advance!
How are you saving your figures? It looks like you may be using savefig(..., bbox_inches='tight') which automatically resized the figure to include all the artists.
If I run your code with fig.savefig(..., bbox_inches=None), I get the following output

pyqt5 QLabel Image setScaledContents(True) don't allow Qpainter updates

I want to display an image and put a marker at the current mouse position for every left mouse click.
Below code does the job however, it works only if ("self.imglabel.setScaledContents(True)") is commented. Any reason?
I have to do this job on various images of different resolutions, I read to maintain the proper aspect ratio and display the image appropriately we need to use setScaledContents(True). But why enabling this is not allowing update() (PaintEvent)??
import sys
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QSizePolicy, QMessageBox
from PyQt5.QtGui import QPixmap, QPainter, QPen, QColor, QImage, QPalette
class Menu(QMainWindow):
def __init__(self):
super().__init__()
self.central_widget = QWidget() # define central widget
self.setCentralWidget(self.central_widget)
self.vbox = QVBoxLayout(self.central_widget)
self.vbox.addWidget(self.imgWidget())
self.vbox.addWidget(QPushButton("test"))
def imgWidget(self):
self.imglabel = QLabel()
self.imglabel.setScaledContents(True)
self.image = QImage("calib.jpeg")
self.imagepix = QPixmap.fromImage(self.image)
self.imglabel.setPixmap(self.imagepix)
self.imglabel.mousePressEvent = self.imgMousePress
return self.imglabel
def imgMousePress(self, e):
painter = QPainter(self.imglabel.pixmap())
pen = QPen()
pen.setWidth(10)
pen.setColor(QColor('red'))
painter.setPen(pen)
painter.drawPoint(e.x(), e.y())
painter.end()
self.imglabel.update()
if __name__ == '__main__':
app = QApplication(sys.argv)
mainMenu = Menu()
mainMenu.show()
sys.exit(app.exec_())
To avoid unnecessary computation for each paintEvent of the QLabel, whenever the scaledContents property is True the scaled image is cached, and all the painting is automatically discarded.
To avoid that, you should create a new instance of QPixmap using the existing one, and then set the new painted pixmap again. Note that if the image is scaled, the widget coordinates won't reflect the actual position on the pixmap, so you need to use a transformation to get the actual point to paint at.
def imgMousePress(self, e):
pm = QPixmap(self.imglabel.pixmap())
painter = QPainter(pm)
pen = QPen()
pen.setWidth(10)
pen.setColor(QColor('red'))
painter.setPen(pen)
transform = QTransform().scale(
pm.width() / self.imglabel.width(),
pm.height() / self.imglabel.height())
painter.drawPoint(transform.map(e.pos()))
painter.end()
self.imglabel.setPixmap(pm)
Consider that all the "points" will become stretched rectangles if the width/height ratio is not the same of the source image, but this is only a problem of appearance: if you save the pixmap later, they will be squares again, since saving is based on the source pixmap.
If you want to keep their squared shape while displaying instead, you'll need to keep track of the points and overwrite paintEvent to paint them manually on the label.

Can I draw TKinter objects on top of an embedded FigureCanvasTkAgg?

shortly said:
I am creating a quick TKinter API and I firstly generate a tk.Canvas
I am embedding a FigureCanvasTkAgg canvas with master = tk.Canvas above
With this I am able to show an image via Matplotlib
Now I want to draw TKinter objects ON TOP of the FigureCanvasTkAgg canvas (e.g. rectangles or buttons)
Is this possible? Or is there any particular recommendation (i.e. using only one canvas or the other)?
Here some quick code:
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
class MyApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.canvas = tk.Canvas(self, width=500, height=500, cursor="cross")
self.canvas.pack(side="top", fill="both", expand=True)
def draw_image_and_button(self):
self.figure_obj = Figure()
a = self.figure_obj.add_axes([0, 0, 1, 1])
imgplot = a.imshow(some_preloaded_data_array, cmap='gray')
# create tkagg canvas
self.canvas_agg = FigureCanvasTkAgg(self.figure_obj, master=self.canvas)
self.canvas_agg.draw()
self.canvas_agg.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
# attempt to draw rectangle
self.rectangle = self.canvas.create_rectangle(0, 0, 100, 100, fill='red')
if __name__ == "__main__":
app = MyApp()
app.draw_image()
app.mainloop()
I mean I see that the rectangle is being drawn before the image. Maybe its my lack of understanding on how FigureCanvasTkAgg is attached to tk.canvas
Thank you!
Ok, this is an app that I recently developed where I have matplotlib widgets and mouse events. You can also have tkinter widgets but I didn't find a way to put them on top of the matplolib canvas. Personally I like matplotlib widgets more than tkinter widgets, so I think it is not too bad.
The only pre-step that you have to take is to modify matplotlib source code because you need pass the canvas to the widget class, while by default the widget takes the figure canvas which will not work when embedding in tk (button would be unresponsive). The modification is actually quite simple, but let's go in order.
Open 'widgets.py' in the matplotlib folder (depending on where you installed it, in my case I have it in "C:\Program Files\Python37\Lib\site-packages\matplotlib").
Go to the class AxesWidget(Widget) (around line 90) and modify the __init__ method with the following code:
def __init__(self, ax, canvas=None):
self.ax = ax
if canvas is None:
self.canvas = ax.figure.canvas
else:
self.canvas = canvas
self.cids = []
As you can see compared to the original code I added a keyword argument canvas=None. In this way the original functionality is mantained, but you can now pass the canvas to the widget.
To have a responsive button on the matplolib canvas that is embedded in tk you now create a widget and you pass the matplolib canvas created with FigureCanvasTkAgg. For example for a Buttonyou would write
from matplotlib.widgets import Button
ok_button = Button(ax_ok_button, 'Ok', canvas=canvas) # canvas created with FigureCanvasTkAgg
Ok now we have all the functionalities required to have matplolib widgets on the matplolib canvas embedded in tk, plus you can also have mouse and key events, which I guess covers 95% of what you expect from a GUI. Note that if you don't want to modify the original source code you can, of course, create your own class copying AxesWidget class.
You find all the available matplolib widgets here https://matplotlib.org/3.1.1/api/widgets_api.html
Here is a modified version of your app where we put everything together:
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
from matplotlib.widgets import Button
import numpy as np
class MyApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.canvas = tk.Canvas(self, width=500, height=500, cursor="cross")
self.canvas.pack(side="top", fill="both", expand=True)
def draw_image_and_button(self):
self.figure_obj = Figure()
self.ax = self.figure_obj.add_subplot()
self.figure_obj.subplots_adjust(bottom=0.25)
some_preloaded_data_array = np.zeros((600,600))
imgplot = self.ax.imshow(some_preloaded_data_array, cmap='gray')
# create tkagg canvas
self.canvas_agg = FigureCanvasTkAgg(self.figure_obj, master=self.canvas)
self.canvas_agg.draw()
self.canvas_agg.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
# add matplolib toolbar
toolbar = NavigationToolbar2Tk(self.canvas_agg, self.canvas)
toolbar.update()
self.canvas_agg._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
# add matplolib widgets
self.ax_ok_B = self.figure_obj.add_subplot(position=[0.2, 0.2, 0.1, 0.03]) # axes position doesn't really matter here because we have the resize event that adjusts widget position
self.ok_B = Button(self.ax_ok_B, 'Ok', canvas=self.canvas_agg)
# add tkinter widgets (outside of the matplolib canvas)
button = tk.Button(master=self, text="Quit", command=self._quit)
button.pack(side=tk.BOTTOM)
# Connect to Events
self.ok_B.on_clicked(self.ok)
self.canvas_agg.mpl_connect('button_press_event', self.press)
self.canvas_agg.mpl_connect('button_release_event', self.release)
self.canvas_agg.mpl_connect('resize_event', self.resize)
self.canvas_agg.mpl_connect("key_press_event", self.on_key_press)
self.protocol("WM_DELETE_WINDOW", self.abort_exec)
def abort_exec(self):
print('Closing with \'x\' is disabled. Please use quit button')
def _quit(self):
print('Bye bye')
self.quit()
self.destroy()
def ok(self, event):
print('Bye bye')
self.quit()
self.destroy()
def press(self, event):
button = event.button
print('You pressed button {}'.format(button))
if event.inaxes == self.ax and event.button == 3:
self.xp = int(event.xdata)
self.yp = int(event.ydata)
self.cid = (self.canvas_agg).mpl_connect('motion_notify_event',
self.draw_line)
self.pltLine = Line2D([self.xp, self.xp], [self.yp, self.yp])
def draw_line(self, event):
if event.inaxes == self.ax and event.button == 3:
self.yd = int(event.ydata)
self.xd = int(event.xdata)
self.pltLine.set_visible(False)
self.pltLine = Line2D([self.xp, self.xd], [self.yp, self.yd], color='r')
self.ax.add_line(self.pltLine)
(self.canvas_agg).draw_idle()
def release(self, event):
button = event.button
(self.canvas_agg).mpl_disconnect(self.cid)
print('You released button {}'.format(button))
def on_key_press(self, event):
print("you pressed {}".format(event.key))
# Resize event is needed if you want your widget to move together with the plot when you resize the window
def resize(self, event):
ax_ok_left, ax_ok_bottom, ax_ok_right, ax_ok_top = self.ax.get_position().get_points().flatten()
B_h = 0.08 # button width
B_w = 0.2 # button height
B_sp = 0.08 # space between plot and button
self.ax_ok_B.set_position([ax_ok_right-B_w, ax_ok_bottom-B_h-B_sp, B_w, B_h])
print('Window was resized')
if __name__ == "__main__":
app = MyApp()
app.draw_image_and_button()
app.mainloop()
Ok let's see the functionalities of this app:
Press a key on the keyboard → print the pressed key
Press a mouse button → print the pressed button (1 = left, 2 = wheel, 3 = right)
Release a mouse button → print the released button
Press the right button on any point on the plot and draw a line while keeping the mouse button down
Press ok or quit to close the application
Pressing 'x' to close the window is disabled.
Resize the window → Plot and widgets scales accordingly
I also took the liberty to add the classic matplotlib toolbar for other functionalities like zooming.
Note that the image plot is added with add_suplot() method which adds the resizing functionality. In this way when you resize the window the plot scales accordingly.
Most of the things I implemented you also find them on the official tutorial from matplotlib on how to embed in tk (https://matplotlib.org/3.1.3/gallery/user_interfaces/embedding_in_tk_sgskip.html).
Let me know if this answers your question. I wanted to share it because I actually developed something very similar a few days ago.

How to set the order of widgets in QGridLayout

I am trying to put a QPushButton on top of a PlotWidget. My current code always has the plot widget on top of the button. How can I bring the button to the front of the QGridLayout?
Or is there a better way in PyQt5 to overlay widgets?
I have tried using .raise__() and .lower__() neither worked as expected.
As far as I found there is no way in PyQt5 to set a z value
Changing the order of adding the widgets to the QGridLayout had no effect
The PlotWindow class is used in a Stacked widget in a Window controller class as well as some other classes
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.central_widget = QtWidgets.QStackedWidget()
self.setCentralWidget(self.central_widget)
self.plot = PlotWindow(self)
self.central_widget.addWidget(self.plot)
self.central_widget.setCurrentWidget(self.plot)
self.show()
class PlotWindow(QtWidgets.QWidget):
def __init__(self, parent=None):
super(PlotWindow, self).__init__(parent)
plot_frame = pyqtgraph.PlotWidget()
self.connect_btn = QtWidgets.QPushButton("Connect", self)
plot_wrapper_layout = QtWidgets.QGridLayout()
plot_wrapper_layout.addWidget(plot_frame, 0, 0, 12, 12)
plot_wrapper_layout.addWidget(self.connect_btn, 11, 11, 1, 1)
self.setLayout(plot_wrapper_layout)
Expecting: Button to be visible on top of the graph in the bottom right corner
Result: The connect button is hidden behind the plot widget
plot_frame = pyqtgraph.PlotWidget(self). That puts the graph widget before the push button in PlotWindow.children() which changes the order in which they are rendered.
Heikie's comment fixed the issue

How to force redraw of a widget after changing some of its attributes?

Inside the call-back associated with a matplotlib.widgets.Slider instance, I want to modify the Slider valmin, valmax and val attributes, and then re-draw the Slider. When I try to re-draw it, nothing happens.
Before the call-back completes, I call plt.draw() and, while the rest of the plot is correctly updated, the Slider looks the same as before. I also tried calling draw() on the Axes of the Slider, and again no visible change.
How can I force a re-draw of the Slider instance after changing its attributes?
Thansk!
UPDATE
Here a small program that demonstrates the issue (with a crude dialog). The wanted behavior is that by clicking on a different value of the radio button, the slider changes range of values, current value and label. What happens instead is that when clicking on "Gradient" the slider stops responding (cannot be dragged anymore), and when clicking on "Gradient" or "Channel" the slider is not updated, in spite of a call to plt.draw()
from matplotlib import pyplot as plt
from matplotlib import gridspec
from matplotlib.widgets import Slider, RadioButtons
# Set the grid
grid = gridspec.GridSpec(2, 1, height_ratios=[1, 2])
# Plot the sliders
axes_slider = plt.subplot(grid[0, 0])
slider = Slider(axes_slider, 'Channel', valmin=0, valmax=255, valinit=128)
# Plot the radio buttons
axes_button = plt.subplot(grid[1, 0])
button = RadioButtons(axes_button, ('Gradient', 'Channel'), active=1)
plt.tight_layout(h_pad=0)
plt.subplots_adjust(left=.2, right=.9)
def update(_):
take_gradient = True if button.value_selected == 'Gradient' else False
if take_gradient:
slider.valmin = -1
slider.valmax = 1
slider.val = 0
slider.label= 'Gradient'
slider.valinit = 0
else:
slider.valmin = 0
slider.valmax = 255
slider.val = 128
slider.label = 'Channel'
slider.valinit = 128
plt.draw()
# Register call-backs with widgets
slider.on_changed(update)
button.on_clicked(update)
plt.show()
The slider itself is a class that hosts and manages some parameters. It does not have a draw method.
That said, it's not enough to only set the parameters of the slider, you would also need to update the axes the slider lives in. At the end this all sums up at doing exactly the steps the slider is doing a initialization, so you can simple call the silder's __init__ function.
I would strongly recommend to use two different functions, one for changing the slider that is called upon button clicks and one for things that should happen if the slider value is adjusted.
Here is a working example:
from matplotlib import pyplot as plt
from matplotlib import gridspec
from matplotlib.widgets import Slider, RadioButtons
# Set the grid
grid = gridspec.GridSpec(2, 1, height_ratios=[1, 2])
# Plot the sliders
axes_slider = plt.subplot(grid[0, 0])
slider = Slider(axes_slider, 'Channel', valmin=0, valmax=255, valinit=128)
# Plot the radio buttons
axes_button = plt.subplot(grid[1, 0])
button = RadioButtons(axes_button, ('Gradient', 'Channel'), active=1)
plt.tight_layout(h_pad=0)
plt.subplots_adjust(left=.2, right=.9)
def buttonupdate(val):
if val == "Gradient":
axes_slider.clear()
slider.__init__(axes_slider, 'Gradient', valmin=-1, valmax=1, valinit=0)
else:
axes_slider.clear()
slider.__init__(axes_slider, 'Channel', valmin=0, valmax=255, valinit=128)
plt.gcf().canvas.draw_idle()
def sliderupdate(val):
if slider.label.get_text() == 'Gradient':
#do something depending on gradient value
pass
else:
#do something depending on channel value
pass
# Register call-backs with widgets
slider.on_changed(sliderupdate)
button.on_clicked(buttonupdate)
plt.show()