Matplotlib Qt4 GUI programming - replace plt.figure() with OO equivalent - python-2.7

I have an App made using Qt4 Designer which inserts a matplotlib figure into a container widget.
The code to generate the figure comes from another module, obspy:
self.st.plot(fig = self.rawDataPlot)
https://docs.obspy.org/packages/autogen/obspy.core.stream.Stream.plot.html
Normally, this would create and show a matplotlib figure for the st object's data, which is time-series. When the fig parameter is specified this tells self.st.plot to plot to an existing matplotlib figure instance.
The code I have to generate the figure and then position it in my GUI widget is:
def addmpl(self, fig, layout, window): # code to add mpl figure to Qt4 widget
self.canvas = FigureCanvas(fig)
layout.addWidget(self.canvas)
self.canvas.draw()
self.toolbar = NavigationToolbar(self.canvas,
window, coordinates=True)
layout.addWidget(self.toolbar)
self.rawDataPlot = plt.figure() # code to create a mpl figure instance
self.st.plot(fig = self.rawDataPlot) # plot time-series data to existing matplotlib figure instance
self.addmpl(self.rawDataPlot, self.mplvl, self.mplwindow) # add mpl figure to Qt4 widget
What I want to do is instantiate a matplot figure (for use by self.st.plot) but in a way which avoids using plt.figure(), as I have read that this is bad practice when using object-oriented programming.
If I replace plt.figure() with Figure() (from matplotlib.figure.Figure()) I get an error:
AttributeError: 'NoneType' object has no attribute 'draw'
As it stands, the App runs fine if I use plt.figure(), but is there a clean way to avoid using is and is it even necessary for my case?
PS, the code snippets here are taken from a larger source, but I think it gets the point across..

In principle both methods should work.
Whether you set self.rawDataPlot = plt.figure() or self.rawDataPlot = Figure() does not make a huge difference, assuming the imports are correct.
So the error is most probably triggered within the self.st.plot() function. (In general, if you report errors, append the traceback.)
Looking at the source of obspy.core.stream.Stream.plot there is a keyword argument
:param draw: If True, the figure canvas is explicitly re-drawn, which
ensures that existing figures are fresh. It makes no difference
for figures that are not yet visible.
Defaults to True.
That means that apparently the plot function tries to draw the canvas, which in the case of providing a Figure() hasn't yet been set.
A good guess would therfore be to call
self.rawDataPlot = Figure()
self.st.plot(fig = self.rawDataPlot, draw=False)
and see if the problem persists.

Related

AttributeError: 'module' object has no attribute 'setup_graph'

I am new to deep learning and trying to implement code written here
http://r2rt.com/recurrent-neural-networks-in-tensorflow-i.html.
I am trying to implement same code but I am getting error
no module name basic_rnn
while importing basic_rnn as written in the code:
import basic_rnn
def plot_learning_curve(num_steps, state_size=4, epochs=1):
global losses, total_loss, final_state, train_step, x, y, init_state
tf.reset_default_graph()
g = tf.get_default_graph()
losses, total_loss, final_state, train_step, x, y, init_state = \
basic_rnn.setup_graph(g,basic_rnn.RNN_config(num_steps=num_steps, state_size=state_size))
res = train_network(epochs, num_steps, state_size=state_size, verbose=False)
plt.plot(res)
then I changed basic_rnn = tf.contrib.rnn.BasicRNNCell,
then I am getting error
'module' object has no attribute 'setup_graph'.
I am assuming I will again get error in while implementing basic_rnn.RNN_config.
What would be the correct syntax?
I am using tensorflow of version 1.0.0
pls help
You can look at the gist code provided by the author, r2rt:
https://gist.github.com/anonymous/5fc9903990ecec5f09361934920bb999. Though you need to tweak the code a bit to get it run.
Basically, you need to implement the setuo_graph and RNN_config functions in basic_rnn.py. But since there are three versions of RNNs that the original blog is comparing, I think it would be better if you put RNN_config in one Python file.
Besides, I found some of r2rt's code is deprecated, so I adapted the code and created my own repo. Check it out if you are interested:
https://github.com/innerfirexy/rnn-tf-r2rt
You can run the code in run_RNNs.py in IPython. I changed the gist code a bit by moving the RNN_config function to train.py, and giving train_network a config parameter.

Overwriting Existing Python Plots with New Function Call

I would like to overwrite an existing plot I made in python with a new function call. I would like to produce a plot, look at it, then call the same function again with different arguments to produce another plot. I would like the second plot to replace the first plot. That is, I don't want two figure windows open; just the original window overwritten.
I have tried using interactive mode when plotting (ion()), placing plot() and show() calls in different places, and clearing figures. The problems I have are that: 1. I can never overwrite and existing window, I always open more 2. show() blocks the code from continuing and I am unable to perform the 2nd function call 3. I use interactive mode and the window appears for a second before going away
What I'm trying to do seems simple enough, but I'm having great difficulty. Any help is appreciated.
Easiest solution
There are many ways to do this, the easiest of which is to reset the plot's Line2D using its set_ydata(...) method and pyplot.pause. There are versions of matplotlib (<0.9, I believe) which don't have pyplot.pause, so you may need to update yours. Here's a simple minimal working example:
import numpy as np
from matplotlib import pyplot as plt
ph, = plt.plot(np.random.rand(100))
def change_plot():
ph.set_ydata(np.random.rand(100))
plt.pause(1)
while True:
change_plot()
Other approaches
Using pyplot.ion and pyplot.ioff, as detailed here. I tend to use these when I'm doing exploratory data analysis with a Python shell.
Using the matplotlib.animation package, as detailed in this very comprehensible example. This is a much more robust approach than the easy solution above, and permits all kinds of useful/fun options, such as outputting the animation to a video file, etc.
Instead of using the set_ydata method of the Lines object, you can always clear the axes (pyplot.cla()) and call the plotting command again. For example, if you are using pyplot.contour, the returned QuadContourSet has no set_zdata method, but this will work:
import numpy as np
from matplotlib import pyplot as plt
X,Y = np.meshgrid(np.arange(100),np.arange(100))
def change_plot():
Z = np.random.random(X.shape)
plt.cla()
ph = plt.contour(X,Y,Z)
plt.pause(1)
while True:
change_plot()
write your plotting function like
def my_plotter(ax, data, style):
ax.cla()
# ax.whatever for the rest of your plotting
return artists_added
and then call it like
data = some_function()
arts = my_plotter(plt.gca(), data, ...)
or do
fig, ax = plt.subplots()
and then call your plotting function like
arts = my_plotter(ax, data, ...)
I had almost the same issue and I solved it by assigning a name for each plot.
def acc(train_acc, test_acc, savename):
plt.figure(savename) # If you remove this line, the plots will be added to the same plot. But, when you assign a figure, each plot will appear in a separate plot.
ep = np.arange(len(train_acc)) + 1
plt.plot(ep, train_acc, color="blue", linewidth=1, linestyle="-", label="Train")
plt.plot(ep, test_acc, color="red", linewidth=1, linestyle="-", label="Test")
plt.title("NDCG")
plt.xlabel("Iteration")
plt.ylabel("NDCG#K")
plt.legend(loc='lower right')
plt.savefig(savename)

automated creation of pdf with Matplotlib blocks the code execution

I have a Python code that contains a function where a figure is created in order to be saved as a pdf (it never shows on the screen during execution). For some reason, the execution of this subroutine keeps the figure open and blocks the following operations in the code. I tried to use the cla(), clf() and clear() functions but I could not get it to work...
Here is a partial view of the subroutine:
def trace_pdf(a,b,c,d):
x = np.linspace(0,100,a)
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.plot(b,c,'b', label='BA',linewidth=3.5)
ax2.set_title('a pdf like no other')
fig2.savefig('file.pdf', format='pdf')
fig2.clf()
fig2.clear()
I do not see why my code is blocked... (I checked that if I comment the call to the trace_pdf function, everything works fine).
So here is what I did to fix my problem. I decided to try to run my function as an independent process so I added to my code:
from multiprocessing import Process, Queue
def trace_pdf(a,b,c,d):
x = np.linspace(0,100,a)
fig2 = plt.figure()
ax2 = fig2.add_subplot(111)
ax2.plot(b,c,'b', label='BA',linewidth=3.5)
ax2.set_title('a pdf like no other')
fig2.savefig('file.pdf', format='pdf')
plt.close()
trace_pdf = Process(target=trace_pdf, args=(a,b,c,d))
trace_pdf.start()
This way, the plt_close() call does not impact the main graphic interface as I believe its action is limited to the separate process... For details regarding running a function as an independent process I used this post.

dynamic graph using matplotlib

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
fig=plt.figure()
ax1=fig.add_subplot(1,1,1)
def animate():
data = np.loadtxt("new.txt")
ax1.plot(data[:,0], data[:,1])
return
ani=animation.FuncAnimation(fig,animate,frames=1000)
plt.show()
the error poping up is
TypeError: animate() takes no argument(1 given)
what to do??
There seem to be two errors in your code:
The file you are trying to read does really not exist or is not readable by your script. (That is why you get the error message.)
As Hima correctly says, the FuncAnimation expects to receive a function (i.e. animate) whereas animate() is the return value of the function.
Then there is one thing you should consider. If your data is in a simple file, you might try using the numpy.loadtxt to read that file. In that case your function animate would be something like:
import numpy as np
def animate():
data = np.loadtxt("myfile.txt")
ax1.plot(data[:,0], data[:,1])
However, even after that you will end up with an increasing number of plots, because every plot command creates a new line. Instead you might want to have a look at the set_xdata method. (As I guess this is a school assignment, I won't give the full solution.)

Good sources on general program layout (preferably Python or C++)

So I can do a little C++ console stuff with classes (nothing too fancy I think) and just started with Python (awesome language, it's like C++ without worries) and Tkinter.
The thing is that I don't really have a clue how in general a program with a GUI is structured. I know you have to separate the interface from the internal workings, but that's about it. As an example I am working on a small app that converts Excel tables to LaTeX tables and so far I have this:
from Tkinter import *
class ExcelToLateX:
def __init__(self,master):
self.convert = Button(master,text="Convert",command=self.Conversion)
self.convert.pack(side=BOTTOM,fill=X)
self.input=Input(master,40)
self.output=Output(master,40)
def Conversion(self):
self.output.Write(self.input.Read())
class Input:
def __init__(self,master,x):
self.u=Text(master,width=x)
self.u.pack(side=LEFT)
self.u.insert(1.0,"Paste Excel data here...")
def Read(self):
return self.u.get(1.0,END)
class Output:
def __init__(self,master,x):
self.v=Text(master,width=x)
self.v.pack(side=RIGHT)
self.v.insert(1.0,"LaTeX code")
def Write (self,input):
self.input=input
if self.v.get(1.0,END)=="":
self.v.insert(1.0,self.input)
else:
self.v.delete(1.0,END)
self.v.insert(1.0,self.input)
#Test script
root=Tk()
Window=ExcelToLateX(root)
root.mainloop()
So I have two Text widgets that can read and write stuff and a (for now) empty conversion class that will take Excel tables and spew out LaTeX code. I have no idea if this is the way to go (so any comments/tips are appreciated).
So in short I have two questions:
Are there any widely acknowledged sources that provide information on how a program with a GUI is structured? (preferably Python and Tkinter because that's what I'm doing right know, although it may be a bit more general (cross-language))
Is my current application any good when it comes to structure, and if not, what are some rules of thumb and things I can improve?
I'm just going to throw a couple short comments into the hat. I don't have experience with Tkinter, so my knowledge derives from PyQt4 experience.
Right now you are using composition for your classes, by making the single widget a member attribute. This can obviously work but a useful pattern is to subclass a GUI widget, and then compose the layout by adding more child widgets and parenting to that class. See the examples on this random Tkinter tutorial link I found: http://zetcode.com/tutorials/tkintertutorial/
class Example(Frame):
def __init__(self, parent):
super(Example, self).__init__(parent)
...
And just as a general python convention, you should try and stick with capitalization for your class names, and camelCase or under_score for class instance methods and variables. As you have it, you are using capital for instances (Window =) and methods (Write)
Also, if you aren't going to be subclassing Tkinter widgets, make sure to at least use the new-style classes by subclassing from object: http://realmike.org/blog/2010/07/18/introduction-to-new-style-classes-in-python/
You might also want to nest that last part of your code where you run the event loop inside of the classic python idiom:
if __name__ == "__main__":
root=Tk()
window = ExcelToLateX(root)
root.mainloop()
It prevents your app from immediately being executed if you were to import this module into another application as a library.