Question

I'm puzzled by the meaning of the 'ax' keyword in the pandas scatter_matrix function:

pd.scatter_matrix(frame, alpha=0.5, figsize=None, ax=None, grid=False, diagonal='hist', marker='.', density_kwds={}, hist_kwds={}, **kwds)

The only clue given in the docstring for the ax keyword is too cryptic for me:

ax : Matplotlib axis object

I had a look in the pandas code for the scatter_matrix function, and the ax variable is incorporated in the following matplotlib subplots call:

fig, axes = plt.subplots(nrows=n, ncols=n, figsize=figsize, ax=ax,
                         squeeze=False)

But, for the life of me, I can't find any reference to an 'ax' keyword in matplotlib subplots!

Can anyone tell me what this ax keyword is for???

Was it helpful?

Solution 2

In short, it targets a subplot within a grid.

If you have nrows=2 and ncols=2, for example, then ax allows you to plot on a specific axis by passing ax=axes[0,0] (top left) or ax=axes[1,1] (bottom right), etc.

When you create the subplots, you receive an axes variable. You can later plot (or subplot) with an element of that axes variable as above.

Take a look at the "Targeting different subplots" section of this page: http://pandas.pydata.org/pandas-docs/dev/visualization.html#targeting-different-subplots

I hope this helps.

OTHER TIPS

This is tricky here. When looking at the source of pandas scatter_matrix you will find this line right after the docstring:

fig, axes = _subplots(nrows=n, ncols=n, figsize=figsize, ax=ax, squeeze=False)

Hence, internally, a new figure, axes combination is created using the internal _subplots method. This is strongly related to the matplotlibs subplots command but slightly different. Here, the ax keyword is supplied as well. If you look at the corresponding source (pandas.tools.plotting._subplots) you will find these lines:

if ax is None:
    fig = plt.figure(**fig_kw)
else:
    fig = ax.get_figure()
    fig.clear()

Hence, if you supply an axes object (e.g. created using matplotlibs subplots command), pandas scatter_matrix grabs the corresponding (matplolib) figure object and deletes its content. Afterwards a new subplots grid is created into this figure object.

All in all, the ax keyword allows to plot the scatter matrix into a given figure (even though IMHO in a slightly strange way).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top