The preferred way to set matplotlib figure/axes properties


Question

Say I have a matplotlib axes called ax, and I want to set several of its properties. Currently, I do it like this:

ax.set_yscale('log')
ax.set_xlim([0,10])
ax.set_xlabel('some label')

But it gets tedious after a while. Then I ran into this method:

ax.set(yscale='log', xlim=[0,10], xlabel='some label')

Much more concise, but it seems a bit undocumented. I mean all the documentation says is "A tkstyle set command, pass kwargs to set properties".

What is the preferred or idiomatic way? Is the set method api stable?

1
22
11/26/2012 4:49:35 PM

Accepted Answer

Pyplot tutorial appears to recommend ax.set_xxx() functions, but also mentions .setp(xxx=).

On the other hand, .set(xxx=) function is not used and .setp(xxx=), while documented, is not used in any examples (Pyplot API).

I understand it that matplotlib supports both imperative programming style and matlab-like style. Reason being the target user bases -- those already familiar with Python and those who used Matlab before.

I conclude that matplotlib recommended api is .set_xxx().

A quick check through the gallery confirms this.

Similar duality exists for keyword arguments to plot functions, except that imperative API is not that obvious.

14
3/19/2014 11:57:43 AM

As a super-late followup to this question:

ax.set_xlim(4) and ax.set(xlim=4) are ultimately the same thing, so do what you like. ax.set(kwarg=foo) calls ax.set_kwarg(foo) via some string manipulation, as you can see if you look at the source. The various setter functions are mostly one-liners, as well, but exist to allow for the introspective setp to work.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon