Overwriting Existing Python Plots with New Function Call - python-2.7

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)

Related

Error using turtle under Python 2.7 Idle

Why is my code showing an error in turtle()? I am using Python 2.7.13 Idle. The query is regarding to draw a square using turtle:
import turtle
def draw_square():
window=turtle.Screen()
window.bgcolor("red")
brad= turtle.Turtle()
brad.shape("yellow") # move forward
brad.speed(2)# turn pen right 90 degrees
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
brad.forward(100)
brad.right(90)
window.exitonclick()
draw_square()
You've made a couple of mistakes in your program. First, the window.exitonclick() isn't indented properly such that you're referencing a local variable of draw_square() from outside the function. Your insanely narrow, one space indentation was likely a contributor to this issue.
The next mistake is brad.shape("yellow") as yellow isn't a shape, it's a color. Also, the comments in draw_square() appear to be on the wrong lines. Some might not consider that a mistake, but I do.
Your code reworked to fix the above and lay it out in a more logical fashion for turtle programming:
import turtle
def draw_square(a_turtle):
a_turtle.forward(100) # move forward
a_turtle.right(90) # turn pen right 90 degrees
a_turtle.forward(100)
a_turtle.right(90)
a_turtle.forward(100)
a_turtle.right(90)
a_turtle.forward(100)
a_turtle.right(90)
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.shape("turtle")
brad.color("yellow")
brad.speed("slow")
draw_square(brad)
turtle.mainloop()

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

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.

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.)

Python: How to import the absolute minimum needed for Matplotlib?

I have a small project that uses matplotlib to display a wafer map of die. I am "compiling" the single-file Python (2.7) into an executable using PyInstaller with the --onefile option, so that non-Python users at the company can execute it in Windows.
The executable takes quite a while to load, up to 15s. As a workaround, I removed all the wafer-map plotting capabilities of the program and built a "Lite" version. This Lite version runs in <1s, as it should. In addition, the Lite version's .exe is 85% smaller (as expected).
So it looks like the Matplotlib stuff is bloating the exe and is making it take a long time to load.
Here's my thought process:
I should be able to get the file size down and decrease the load time if I only import the modules I use rather than all of matplotlib.pyplot. I assume that the import matplotlib.pyplot as pyplot line is importing a whole bunch of extra stuff that I'm not using, such as scatterplots.
Here's my question:
How can I only import the parts of matplotlib that I use?
Here's my (relevant) code, with a lot of the fluff (like line colors) removed. Also, please ignore the lack of PEP8 conformity - this was written before I decided to follow it :-)
from __future__ import print_function
import math
import matplotlib.pyplot as pyplot
import matplotlib.patches
fig = pyplot.figure(1)
ax = fig.add_subplot(111, aspect='equal')
ax.axis([xAxisMin, xAxisMax, yAxisMin, yAxisMax])
die = matplotlib.patches.Rectangle(coords, dieX, dieY)
ax.add_patch(die)
arc = matplotlib.patches.Arc((0, 0),
width=exclDia, height=exclDia, angle=-90,
theta1=ang, theta2=-ang)
flat = matplotlib.lines.Line2D([-flatX, flatX],
[flatY, flatY])
# Extra code that actually adds everything to the figure
fig.show()
So it looks like I'm using only:
matplotlib.pyplot.figure
matplotlib.patches.Rectangle
matplotlib.patches.Arc
matplotlib.lines.Line2D
However, those above are not individual modules in matplotlib (to my knowledge) - they are classes of their parent module (patches, lines, pyplot), so I can't just `import matplotlib.patches.Arc' or anything.
So. What's my next step?