user
user

Reputation: 771

How to loop through axis elements in a series of subplots?

I have a series of subplots created using sns.FacetGrid, and mapping with sns.scatterplot. It generates 13 subplots. The plotting part works perfectly and does not need to be changed.

I am aiming to add a diagonal line to each subplot.

The best method I have found so far employs the following:

h = sns.FacetGrid(df, hue="category", col="category_2", col_wrap=3)
h.map(sns.scatterplot, "x", "y", s=75, alpha=0.4)

# get axes
ax1, ax2, ax3, ax4, ax5, ax6, ax7, ax8, ax9, ax10, ax11, ax12, ax13 = h.axes

ax1.plot([-1, 6], [-1, 6], transform=ax1.transAxes, ls="--", c="k")
ax2.plot([-1, 6], [-1, 6], transform=ax2.transAxes, ls="--", c="k")
... 
ax13.plot([-1, 6], [-1, 6], transform=ax2.transAxes, ls="--", c="k")

This is a very basic question... what is the best way to iterate through each ax.plot so I do not have to copy and paste that line 13 times?

These methods below do not work, because in the first case axi is not defined and in the second the f-string makes it a string object which cannot plot.

for i in range(1,14):
    axi.plot([-1, 6], [-1, 6], transform=axi.transAxes, ls="--", c="k")

and

for i in range(1,14):
   ax = f"ax{i}"
   ax.plot([-1, 6], [-1, 6], transform=axi.transAxes, ls="--", c="k")

Upvotes: 1

Views: 183

Answers (1)

William Baker Morrison
William Baker Morrison

Reputation: 1789

You can use the map.axes.flat functionality:

for ax in h.axes.flat:
    ax.axline((0, 0), slope=.2, c=".2", ls="--", zorder=0)

And parameters for axline can be found here

Upvotes: 1

Related Questions