matplotlib subplot is slow

Hi all,

I was surprised today to notice that “subplot” was the slowest part of some plotting code of mine.

On my machine, the last line of the following code puts ten subplots on a figure and records the amount of time it took to make them:

import matplotlib

matplotlib.use(‘AGG’)

import time

from matplotlib.pyplot import *

def f():

… t = time.time()

… clf()

… for i in xrange(10):

… subplot(5,2,i+1)

… return time.time()-t

times = [f() for x in xrange(10)]

This code gives me a bunch of times that are on average about half a second. I expected it to be much faster as I wasn’t actually plotting anything.

Is this expected? Can I choose a faster backend or something? I’ve experimented a little but without success. I realize that 5 hundredths of a second per subplot isn’t terrifically slow, … but I guess I make a lot of plots.

Thanks a lot,

Eddie Schlafly

Eddie,

Calling pyplot.subplot() may be slow because it has to determine which figure is the currently active figure, and then create a new axes object for that figure. I would suspect that passing in the figure object and calling add_subplot from the figure may speed things up.

Also note that v1.0.0 introduced pyplot.subplots() which will create a figure, and an array of subplots all at once. There is also the gridspec method that might also be of interest.

I hope that helps!
Ben Root

···

On Thu, Mar 31, 2011 at 7:42 PM, Eddie Schlafly <schlafly@…32…> wrote:

Hi all,

I was surprised today to notice that “subplot” was the slowest part of some plotting code of mine.

On my machine, the last line of the following code puts ten subplots on a figure and records the amount of time it took to make them:

import matplotlib

matplotlib.use(‘AGG’)

import time

from matplotlib.pyplot import *

def f():

… t = time.time()

… clf()

… for i in xrange(10):

… subplot(5,2,i+1)

… return time.time()-t

times = [f() for x in xrange(10)]

This code gives me a bunch of times that are on average about half a second. I expected it to be much faster as I wasn’t actually plotting anything.

Is this expected? Can I choose a faster backend or something? I’ve experimented a little but without success. I realize that 5 hundredths of a second per subplot isn’t terrifically slow, … but I guess I make a lot of plots.

Thanks a lot,

Eddie Schlafly