7

Most seaborn plotting functions (e.g. seaborn.barplot, seaborn.regplot) return a matplotlib.pyplot.axes when called, so that you can use this object to further customize the plot as you see fit.

However, I wanted to create an seaborn.lmplot, which doesn't return the axes object. After digging through the documentation of both seaborn.lmplot and seaborn.FacetGrid (which lmplot uses in it's backend), I found no way of accessing the underlying axes objects. Moreover, while most other seaborn functions allow you to pass your own axes as a parameter on which they will draw the plot on, lmplot doesn't.

One thing I thought of is using plt.gca(), but that only returns the last axes object of the grid.

Is there any way of accessing the axes objects in seaborn.lmplot or seaborn.FacetGrid?

nazz
  • 73
  • 1
  • 1
  • 3

1 Answers1

8

Yes, you can access the matplotlib.pyplot.axes object like this:

import seaborn as sns
lm = sns.lmplot(...)  # draw a grid of plots
ax = lm.axes  # access a grid of 'axes' objects

Here, ax is an array containing all axes objects in the subplot. You can access each one like this:

ax.shape  # see the shape of the array containing the 'axes' objects
ax[0, 0]  # the top-left (first) subplot 
ax[i, j]  # the subplot on the i-th row of the j-th column

If there is only one subplot you can either access it as I showed above (with ax[0, 0]) or as you said in your question through (plt.gca())

Djib2011
  • 6,874
  • 5
  • 36
  • 41