3

I'd like to combine interactive plotting in Matplotlib and the Command line interface Cmd in python. How can I do this? Can I use threading? I tried the following:

from cmd import Cmd
import matplotlib.pylab as plt
from threading import Thread

class MyCmd(Cmd):

    def __init__(self):
        Cmd.__init__(self)
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(1,1,1)

    def do_foo(self, arg):
        self.ax.plot(range(10))
        self.fig.canvas.draw()

if __name__=='__main__':
    c = MyCmd()
    Thread(target=c.cmdloop).start()
    plt.show()

It opens a figure window and I can type commands in the console that are actually executed. When the "foo" command is executed it draws in the figure window. So far everything is ok. When I reenter the console, however, the console seems to be stuck and there is now new command window. But when I click into the figure window the console outputs a new command prompt and I can enter a new command. It seems the two loops are not really interleaved or something. Is there a better, more common way?

3
  • Please edit your question. While editing, please read the instructions for formatting on the right side of the page. Please edit your code to look like code. Commented Aug 12, 2010 at 21:14
  • How does it not work? What version of Python are you using? What platform? How is Thread defined (you don't appear to be importing it)? Commented Aug 12, 2010 at 22:06
  • I'm using Python 2.6 on Linux. Commented Aug 13, 2010 at 6:01

2 Answers 2

3

I found something that works, but is rather ugly

from cmd import Cmd
import matplotlib.pylab as plt
from threading import Thread
import time

class MyCmd(Cmd):

    def __init__(self):
        Cmd.__init__(self)
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(1,1,1)

    def do_foo(self, arg):
        self.ax.plot(range(10))
        self.fig.canvas.draw()

if __name__=='__main__':
    plt.ion()
    c = MyCmd()
    def loop():
        while True:
            c.fig.canvas.draw()
            time.sleep(0.1)
    Thread(target=loop).start()
    c.cmdloop()

This simply calls the draw method of the figure periodically. If I don't do this, the figure is not redrawn, when it was occluded and comes to the front again.

But this seems ugly. Is there a better way?

Sign up to request clarification or add additional context in comments.

Comments

0

iPython is an pretty popular. Take a look at Using matplotlib in a python shell.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.