How can I condense a series of seaborn scatterplots using for loops?

109 views Asked by At

does anyone know how I could use a for loop to iterate through this?

sns.FacetGrid(iris, hue = "Species").map(sns.scatterplot, "Sepal Length", "Sepal Width").add_legend()
sns.FacetGrid(iris, hue = "Species").map(sns.scatterplot, "Petal Length", "Petal Width").add_legend()
sns.FacetGrid(iris, hue = "Species").map(sns.scatterplot, "Sepal Length", "Petal Width").add_legend()
sns.FacetGrid(iris, hue = "Species").map(sns.scatterplot, "Petal Length", "Sepal Width").add_legend()
sns.FacetGrid(iris, hue = "Species").map(sns.scatterplot, "Sepal Length", "Petal Length").add_legend()
sns.FacetGrid(iris, hue = "Species").map(sns.scatterplot, "Petal Width", "Sepal Width").add_legend()

For histplots, that's easy enough, but I'm trying to condense this piece of code for scatterplots with no success. I think I need to loop through a unique pair of columns each time, but I have no idea how to do that. Or even if that's the right thing to do. The data is from the Iris data set: http://archive.ics.uci.edu/ml/datasets/Iris

*I'm aware that this is quite futile, I just wanted to avoid repetitions in the code...

Thanks,

Caio

1

There are 1 answers

1
asdf101 On BEST ANSWER

Looping over two lists at once with the values you need might work:

first_names = ["Sepal Length", "Petal Length", "Sepal Length", "Petal Length", "Sepal Length", "Petal Width"]
second_names = ["Sepal Width", "Petal Width", "Petal Width", "Sepal Width", "Petal Length", "Sepal Width"]

for first_name, second_name in zip(first_names, second_names):
    sns.FacetGrid(iris, hue = "Species").map(sns.scatterplot, first_name, second_name).add_legend()

If you want to get all possible combinations of Sepal Length/Width and Petal Length/Width (didn't look like it in your current code though), you could use this:

names = ["Sepal Length", "Sepal Width", "Petal Length", "Petal Width"]

for first_name in names:
    for second_name in names:
        sns.FacetGrid(iris, hue = "Species").map(sns.scatterplot, first_name, second_name).add_legend()