【问题标题】:How can I condense a series of seaborn scatterplots using for loops?如何使用 for 循环压缩一系列 seaborn 散点图?
【发布时间】:2021-04-18 15:10:23
【问题描述】:

有谁知道我如何使用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,这很容易,但我试图将这段代码压缩为散点图,但没有成功。我想我每次都需要遍历一对独特的列,但我不知道该怎么做。或者即使这是正确的做法。数据来自 Iris 数据集:http://archive.ics.uci.edu/ml/datasets/Iris

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

谢谢,

菜鸟

【问题讨论】:

    标签: python for-loop seaborn scatter-plot iris-dataset


    【解决方案1】:

    使用您需要的值一次循环两个列表可能会起作用:

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

    如果您想获得萼片长度/宽度和花瓣长度/宽度的所有可能组合(但在您当前的代码中看起来不像),您可以使用这个:

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

    【讨论】:

    • 在最后一个示例中,您可以添加一个测试 if first_name < second_name: 以避免身份和双打。这里< 是为了测试一个字符串是否在另一个之前出现。
    猜你喜欢
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 2016-01-30
    • 2018-02-11
    • 2019-09-26
    相关资源
    最近更新 更多