0

I'm trying to create 9 scatterplots using a target variable and 9 continuous variables.

I couldn't figure out a way to loop over each axis to plot scatterplots of each continuous variable against the target.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

fig, ax = plt.subplots(nrows=5, ncols=3, figsize=(16, 8))
sns.scatterplot(x=df['cont0'], y=df['target'], ax=ax[0, 0])
sns.scatterplot(x=df['cont1'], y=df['target'], ax=ax[0, 1])
sns.scatterplot(x=df['cont2'], y=df['target'], ax=ax[0, 2])
sns.scatterplot(x=df['cont3'], y=df['target'], ax=ax[1, 0])
sns.scatterplot(x=df['cont4'], y=df['target'], ax=ax[1, 1])
sns.scatterplot(x=df['cont5'], y=df['target'], ax=ax[1, 2])
sns.scatterplot(x=df['cont6'], y=df['target'], ax=ax[2, 0])
sns.scatterplot(x=df['cont7'], y=df['target'], ax=ax[2, 1])
sns.scatterplot(x=df['cont8'], y=df['target'], ax=ax[2, 2])

How can I do this more efficiently?

  • Middle part of this [answer](https://stackoverflow.com/a/66052914/7758804): `for i, a_x in enumerate(ax.flatten()): sns.scatterplot(x=df[f'cont{i}'], y=df['target'], ax=a_x)`. – Trenton McKinney Sep 05 '21 at 14:55
  • Thanks, this works for 9 variables. If I have 14 numerical variables and use a 5x3 grid, I get ```KeyError: 'cont14'```. Is there a way to tell the for loop that I have 14 scatter plots? – OrangeChutney Sep 05 '21 at 15:45
  • You may have to adjust the pattern (`f'cont{i}'`) if the column names change. Otherwise use something more like option 2 of this answer where you create a list of the desired column names, zip them to the axes, and iterate. – Trenton McKinney Sep 05 '21 at 16:16
  • It sounds like there are more `axes` the subplots. A simple solution would be to add `if i < 14:` into the loop before plotting. – Trenton McKinney Sep 05 '21 at 16:18

0 Answers0