Plot a function during debugging in Python - python

I used to work in Matlab and it is really convenient (when working with big arrays/matrices and nested functions) to visualize intermediate results during debugging using plot function.
In Python I cannot plot anything in debug mode: a window with figure plot is never loaded (I am using Spyder IDE for coding and matplotlib.pyplot for plotting).
This is really annoying when debugging nested function and classes.
Does anyone know a good solution? Of course, I can always output intermediate results, however it is not convenient.
Thanks,
Mikhail

Ok, I found a way to show the plot without breaking the debugging process.
All you need to do is to issue plt.pause(1) command, which will display the plots, and then one can continue the debugging process.

Related

Simplest way to publish matplotlib-like interactive animation to html?

I'm using matplotlib and python to make an animated scatter plot with points as 'balls' that bounce around, just like this:
https://jakevdp.github.io/downloads/videos/particle_box.mp4
It is interactive at runtime (with sliders to change velocity, attraction, etc), simulating on the go.
I would like to then publish it with the interactivity and all in html.
Problem: I don't know of a way to publish matplotlib interactivity to html directly.
So can I do it in python? Or is there a better way?
Which library (or program, if different from python) would you recommend as the simplest and fastest for this kind of project? I don't need "pretty" customizations and all that, I just need easy calculations and simulations (python) to then plot in a few easy lines of code (matplotlib). I do need to change the dots (balls) colors though.
I have looked at mpld3 that should wrap matplotlib around D3js. But I don't know anything about js and it is not very straightforward, so it would take me a bit to learn.
I have also looked at plotly, but it doesn't seem to have the same customization of the animation I need.
I have looked at Dash with plotly, but it would be a whole new environment to learn, and definitely overkill.
So the questions are: is there a way to output matplotlib interactive animations to html that I haven't found?
If not, what tools would you use to accomplish this project within a fast timeframe and shallow learning curve, based on my beginner/low intermediate python and matplotlib skill level?
Thank you!

Is there an equivalent to the Matlab figure window in Python (with all tools)?

I'm just wondering if it exists an equivalent to the Matlab figure window in Python where we can modify plots directly from the figure window, or add some features (text, box , arrow, and so on), or make curve fitting, etc.
Matplotlib is good, but it is not as high-level as the Matlab figure. We need to code everything and if we want to modify plots, we need to modify the code directly (except for some basic stuffs like modifing the line color)
With matplotlib, you will indeed remain in the "code it all" workflow. This is not directly the answer you expect but the matplotlib documentation recently gained a very instructive figure that will probably help you if you stay with matplotlib: http://matplotlib.org/examples/showcase/anatomy.html shows the "anatomy" of the figure with all the proper designations for the parts of the figure.
Overall, I could always find examples of what I needed in their excellent gallery http://matplotlib.org/gallery.html
In my opinion, you'll save time by coding these customizations instead of doing them by hand. You may indeed feel otherwise but if not there is a ton of examples of matplotlib code on SO, in their docs and a large community of people around it :-)

LightTable and matplotlib subplots

While there are a few things that are still being worked out, I am a big fan of the LightTable editor. The IPython Notebook is a remarkable delivery system, but managing a larger product is a bit easier in a more conventional development environment.
One thing that I have not yet figured out, however, is complicated plotting in LightTable. With no cell equivalent, I am not sure how to modify plot components because each command seems to be considered independently. In particular, I am not clear on how to work with subplots. I am unable to connect the actual plot to the subplot array. For example, consider the following:
fig,ax=plt.subplots(2)
ax[0].hist(np.random.uniform(size=100))
ax[1].hist(np.random.normal(size=100))
When I create the subplots, they show up empty inline. The remaining code, however, does not cause them to update inline. In the Notebook, all the code is considered jointly in batch. LightTable interactivity is a bit closer to dealing with an interpreter in interactive mode (even though the script is obviously preserved). I have experiemented with turning interactivity on and off via plt.ioff(), but to no avail. Any assistance would be greatly appreciated...

Save figure parameters after interactive tweaking

I often find myself using matplotlib to quickly display data, then later going back and tweaking my plotting code to make pretty figures. In this process, I often use the interactive plot window to adjust things like spacing, zooming, cropping, etc. While I can easily save the resulting figure to an image file, what I really want is to save the sequence of function calls/parameters that produced it.
Note that I don't particularly care to open the same figure again (as in Saving interactive Matplotlib figures). Even something as simple as being able to print the various properties of the figure and axes would be useful.
While I don't have the answer to your specific question, I'd generally suggest using the Ipython Notebook for these things (and much more!)
Make sure you have %pylab inline in one cell.
When you plot, it will display it in the notebook itself. Then within your cell, just keep experimenting until you have it right (use Ctrl-Enter in the cell). Now the cell will have all the statements you need (and no more!)
The difference between the command line interpreter and the notebook is that the former all statements you typed which leads to a lot of clutter. With the notebook you can edit the line in place.
A similar question here
has an answer I just posted here.
The gist: use MatPlotLib's picklable figure object to save the figure object to a file. See the aforementioned answer for a full example.
Here's a shortened example:
fig, ax = matplotlib.pyplot.subplots()
# plot some stuff
import pickle
pickle.dump( fig, open('SaveToFile.pickle', 'wb') )
This does indeed save all plotting tweaks, even those made by the GUI subplot-adjuster. Unpickling via pickle.load() still allows you to interact via CLI or GUI.

Minimalistic Real-Time Plotting in Python

I've been using python extensively to extract data from various external pieces of equipment (ranging from arduinos to oscilloscopes), and I'm looking for a simplistic way to plot stuff.
There's already some answers to similar questions on stack overflow:
What is the best real time plotting widget for wxPython?
With most pointing to this fine piece of code by Eli Bendersky
http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/
But the scope of the code is far more complicated that what I'm looking for. I'm looking for something rather minimalistic that just plots the data in real-time as it streams from a source -- it doesn't need a GUI, radio buttons, knobs and sliders, or anything like that.
It seems that solutions such as calling pylab.plot() or pylab.show() in a loop doesn't seem to give the correct behavior.
Does anyone have suggestions?
Well, this isn't a wxPython answer but I've used Chaco for this sort of thing and it's pretty straight forward. There is a nice example of a realtime spectrum analyzer that may be similar to your use case and a nice tutorial. So, if you aren't tied to wxPython for other reasons, that might be worth a look.
Besides the matplotlib examples you've found, there's also wx.lib.plot and several answers here: http://wxpython-users.1045709.n5.nabble.com/real-time-data-plots-td2344816.html
To use real time plotting you need to send signals to the GUI loop. If you use interactive mode (Ipython) then you might also like to use threads.
I have written some decorators to handle the GUI and threading in a really easy and clean way. They work for the QT backend.
https://gist.github.com/Vrekrer/106c49a3ae6d420937aa
A sample code for Ipython will look like this
#%pylab qt
#https://gist.github.com/Vrekrer/106c49a3ae6d420937aa
import QThreadDecorators
import time
#QThreadDecorators.GUI_Safe
def myplot(x,y):
#This will plot a new line for each call (ok for an example)
plot(x, y, 'bo-')
grid(True)
#QThreadDecorators.AsQThread
def myLoop(x):
y = x * nan
for i, xi in enumerate(x):
#get some data
time.sleep(1)
y[i] = xi**2
#plot in real time
myplot(x,y)
#just call the function and it will run on a thread
myLoop( arange(20) )

Categories