Drawing in a matplotlib widget in QtDesigner - python

I created in QtDesigner this QDialog:
I would like to know how can I draw something in this Matplotlib widget that I put there. I mean, if I write some code to create a matplotlib figure without Qt Designer, I can write something like:
self.figure_canvas = FigureCanvas(Figure())
self.axes = self.figure_canvas.figure.add_subplot(111)
x = np.arange(0,5,0.5)
y = np.sin(x)
and then draw doing:
ax.plot(x,y) or self.axes.plot(x,y)
How can I access to this widget to draw something? Hope you can help me.

Based on the screenshot that you have provided, it seems that the MatplotlibWidget should be accessible as self.matplotlibwidget from within your QMainWindow class. This is because of the value listed in the "Object" column of the Object Inspector.
You can use this object directly to add plots to your GUI.
self.matplotlibwidget.axes.plot(x, y)

Related

How to make a label inside a PlotWidget?

I'm making a GUI using Qt and pyqtgraph. It's got several PlotWidgets in it - here's a section of it:
I'd like to include the mouse cursor position (in scaled units) as a label within the plot, a bit like the pyqtgraph crosshair example:
The example works by adding a LabelItem to a GraphicsWindow like this:
win = pg.GraphicsWindow()
label = pg.LabelItem(justify='right')
p1 = win.addPlot(row=1, col=0)
But I don't have a GraphicsWindow, just a normal Qt window (built using the Designer) with PlotWidgets in it. I can't seem to add a LabelItem or a TextItem to a PlotWidget. I'm sure there must be a 'standard' way of doing this, but I can't figure it out and Google doesn't seem to know. Any ideas?
Edit: here's a snippet of my code from the window's __init__ function:
self.B_field_plot.setLabels(title='Magnetic field', left='B [T]', bottom='z [m]')
self.label = pg.LabelItem(justify="right")
self.B_field_plot.addItem(self.label)
self.label.setText('Hello')
The label does not appear.
Although it is a bit late now to answer this question, but I will put my answer in case someone else needed it.
You have to change the source file generated by the QTdesigner.
find the line that creates the plotwidget and embedded the title in it.
self.plot = PlotWidget(title= "something")

How to animate the background color of a QPushButton in qt?

I did everything [till what i know] to animate the background color of a button but i can't do it. Here are one of my tries:
# I set the style of the button by setstylesheet()
animation = QPropertyAnimation(btn, "style",btn)
animation.setDuration(1000)
animation.setStartValue(QStyle("background-color:blue"))
animation.setEndValue(QStyle("background-color:red"))
animation.start()
But the following code shows the following error:
animation.setStartValue(QStyle("background-color:blue"))
TypeError: PyQt4.QtGui.QStyle represents a C++ abstract class and cannot be instantiated
I also tried to set a palette:
color = install_btn.palette()
color.setColor(QPalette.Base,QColor(72, 152, 219))
install_btn.setAutoFillBackground(True)
install_btn.setPalette(color)
and then instead of QStyle in above animation value i wrote QColor(r,g,b) but that too didn't worked, it said:
QPropertyAnimation: you're trying to animate a non-existing property style of your QObject
Please help me in any language you know (C++ or Python). But i use Python.
Thanks is special
C++, Qt5, but may work in Qt4
QGraphicsColorizeEffect *eEffect= new QGraphicsColorizeEffect(btn);
btn->setGraphicsEffect(eEffect);
QPropertyAnimation *paAnimation = new QPropertyAnimation(eEffect,"color");
paAnimation->setStartValue(QColor(Qt::blue));
paAnimation->setEndValue(QColor(Qt::red));
paAnimation->setDuration(1000);
paAnimation->start();

Tkinter keeps creating embedded plots instead of updating the current plot

I am aware that there are couple of questions on this around the web but unfortunately none of those helped me with this. My relevant matplotlib imports are:
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
Below is how I call for new plots:
self.myFig1 = Figure(figsize = (10, 4), tight_layout = True)
self.myPlot1 = self.myFig1.add_subplot(111)
self.myPlot1.plot([blah],[blah])
canvas1 = FigureCanvasTkAgg(self.myFig1, self.myFrame)
canvas1.show()
canvas1.get_tk_widget().grid()
I have a refresh button that sort of keeps calling the function that ends up creating this plot, but I need one embedded plot which is updated after every button click, not recreated. I have tried things like Figure.close(), Figure.clf() but none worked. I'd appreciate your help with this.
Additional info: The reason it keeps creating a new plot is because I keep .grid-ing it over and over again. So I deleted the .grid() part of the code and I tried something like this below which did not work:
self.myFig1.clf()
self.myFig1 = Figure(figsize = (10, 4), tight_layout = True)
self.myPlot1 = self.myFig1.add_subplot(111)
self.myPlot1.plot([blah],[blah])
canvas1 = FigureCanvasTkAgg(self.myFig1, self.myFrame)
canvas1.draw()
This just destroys the figure, canvas, everything and doesn't plot anything.
self.myFig.clear()
self.myPlot = self.myFig.add_subplot(111, **self.nadalkwArgs)
self.myPlot.plot([series1], [series2])
self.myFig.canvas.draw()
Is what solved my problem. Your "refresh plot" button or method should have this in order to keep the canvas, clear the old plot, make the new plot and keep plot style elements such as xlabel, ylabel etc. So basically, first you clear the figure(not the subplot, self.myPlot.clear() would clear the plot but you can't have your kwargs that way), and then you recreate the subplot with kwargs and then you plot, and finally you .canvas.draw()
There is no need to recreate a new canvas or fig.
After grid your FigureCanvasTkAgg, you can reset line in button callback only by:
self.myPlot1.set_data(xdata,ydata)
self.myFig.canvas.draw()

Print variable in large font in python figure

I have borrowed some code from another source and I want to edit the figure produced. Here is the relevant (i think) code from the script.
import gtk #the gui toolkit we'll use:
from matplotlib.figure import Figure
from Tkinter import *
from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas
#create a window to put the plot in
win = gtk.Window()
#connect the destroy signal (clicking the x in the corner)
win.connect("destroy", quit_app)
win.set_default_size(600,500)
#create a plot:
fig = Figure()
ax = fig.add_subplot(111,xlabel='Time Step', ylabel='Temp (deg C)', axisbg='black')
ax.set_ylim(0,100) # set limits of y axis.
canvas = FigureCanvas(fig) #put the plot onto a canvas
win.add(canvas) #put the canvas in the window
#show the window
win.show_all()
win.set_title("ready to receive data");
line, = ax.plot(times,yvals, color='red')
while(1):
line.set_ydata(yvals) # draw the line
fig.canvas.draw() # update the Canvas
win.set_title("Temp: "+str(yvals[49])+" deg C")
I don't know whether or not all the code above is necessary - but that is all the 'plot' related code I could find.
So anyway the code works in my program perfectly.
There are TWO tasks I would like to create:
(1) What I want is to include that 'str(yvals[49])' variable, which is currently being displayed in the title of the window, to be displayed in large font underneath the plot. So I think I need to make the window size a little bigger to accompany the text but not sure how to print it.
(2) I manged to change the background of the plot itself to black that plots a red line. But how can I change the background of the window itself to all black and the x/y axis to red as well.
Thanks!!
(1) What you are most probably looking for it the matplotlib text command. Have a look at http://matplotlib.org/users/pyplot_tutorial.html section working with text. It might be convenient to create two separate axes, so you can truly put the text below the whole figure. Maybe it is enough to place the text at xlabel position?
import matplotlib.pyplot as plt
plt.xlabel('yourtext')
(2) There are already good answers out there that might help you: e.g. How to change the pylab window background color?
As for the color of the axis Changing the color of the axis, ticks and labels for a plot in matplotlib
Have also a look at Matplotlib figure facecolor (background color) in case you want to save the figure.

Python and Interactive Zoom Plot with Matplotlib

I am using a Matplotlib plot (with Basemap) inside of a wxPython pane. I have got the plot (US map with scatter plot of cities). I am trying to do some interactive zoom capabilities (select a box on the map and "zoom" into that area only).
I have managed to get the toolbar to show, but when i click on the buttons, nothing happens. Seems like the toolbar is just there for show. Any Thoughts? Here is my code:
# Set up area for plotting Basemap Plot and scatter plot
self.figure = Figure(None,dpi=75)
self.canvas = FigureCanvas(self.PlotPanel, -1, self.figure)
self.axes = self.figure.add_axes([0,0,1,1],frameon=False)
self.SetColor( (255,255,255) )
# Toolbar Set up
self.toolbar=NavigationToolbar2Wx(self.canvas)
self.toolbar.Realize()
tw,th = self.toolbar.GetSizeTuple()
fw,fh = self.canvas.GetSizeTuple()
self.toolbar.SetSize(wx.Size(fw,th))
sizer_7.Add(self.toolbar,0)
self.toolbar.update()
Have a look at the embedding_in_wx2 example, which works fine for me.
Maybe there is something wrong with your imports: you first have to import matplotlib, than set the backend (matplotlib.use('WXagg')) and then import the backend.
However it isn't easy to help you without having a full example with all imports.

Categories