jruota
jruota

Reputation: 147

Passing arguments to plt.savefig in Matplotlib

I wrote a function to save plots in Matplotlib. When I wanted to use it by calling plt.savefig(fname=path, dpi=dpi, format=ext, bbox_inches="tight") I got the following error.

  File "/home/jruota/.local/lib/python2.7/site-packages/matplotlib/pyplot.py", line 697, in savefig
    res = fig.savefig(*args, **kwargs)
  File "/home/jruota/.local/lib/python2.7/site-packages/matplotlib/figure.py", line 1572, in savefig
    self.canvas.print_figure(*args, **kwargs)
TypeError: print_figure() takes at least 2 arguments (5 given)

This error does not occur when I change the call to plt.savefig(path, dpi=dpi, format=ext, bbox_inches="tight"). My guess is this error has something to do with the * and ** argument packing and unpacking but I am unsure how exactly. Any explanation would be appreciated.

Upvotes: 1

Views: 7620

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339062

First, it's clear that if

plt.savefig(path, dpi=dpi, format=ext, bbox_inches="tight")

is working fine, you may simply use it.

The error comes from fname not being a named argument. The documentation may be a bit confusing for people not familiar with call signatures in python at this point.

The signature is matplotlib.pyplot.savefig(*args, **kwargs), where an argument fname needs to be set and further keyword arguments can be specified. The argument must not be a keyword argument of course. So in

fname = "myfile.png"
plt.savefig(fname, dpi=100)

fname is the argument, while in

fname = "myfile.png"
plt.savefig(fname=fname, dpi=100)

fname is a keyword argument, such that no argument specifying the filename is found.

You may test with a self-defined function, if you want:

def f(*args,**kwargs):
    print "args: ",  args
    print "kwargs: ", kwargs

Then

f("q", k="W")  # prints args:  ('q',)
               #        kwargs:  {'k': 'W'}

while

f(fname="q", k="W") # prints args:  ()
                    #        kwargs:  {'k': 'W', 'fname': 'q'}

In the latter case args is empty.

Upvotes: 6

Related Questions