如何使用 for 循环压缩一系列 seaborn 散点图?

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

有谁知道我如何使用 for 循环来遍历这个?

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()

对于 histplots,这很容易,但我试图为散点图压缩这段代码但没有成功。我想我每次都需要遍历一对独特的列,但我不知道该怎么做。或者即使这是正确的做法。数据来自鸢尾花数据集:http://archive.ics.uci.edu/ml/datasets/Iris

*我知道这是徒劳的,我只是想避免代码中的重复...

谢谢,

蔡欧

使用您需要的值同时遍历两个列表可能会奏效:

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()

如果你想获得萼片 Length/Width 和花瓣 Length/Width 的所有可能组合(虽然在你当前的代码中看起来不像),你可以使用这个:

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()