【问题标题】:Differences in Seaborn's scatterplot and lmplot parametersSeaborn 的散点图和 lmplot 参数的差异
【发布时间】:2019-08-29 04:18:13
【问题描述】:

一些快速加载:

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

di = sns.load_dataset('iris')

使用此处的示例虹膜数据集。如下所示轻松创建散点图:

sns.scatterplot(x=di['sepal_length'], y=di['sepal_width'], 
            hue=di['species']);

但是,使用 lmplot 会引发 TypeError 并需要 data 参数。完成 data 参数后,它仍然不起作用:

sns.lmplot(x=di['sepal_length'], y=di['sepal_width'], 
            hue=di['species'], data=di);

TypeError: '<' not supported between instances of 'str' and 'float'

但是,这很好用:

sns.lmplot(x='sepal_length', y='sepal_width', hue='species', data=di);

阅读API reference 后,我看到 lmplot 需要 data 参数,但 scatterplot 不需要。这里有什么不同的东西吗?还有什么是这里语法的最佳实践。

【问题讨论】:

    标签: python python-3.x pandas matplotlib seaborn


    【解决方案1】:

    您的代码不起作用的原因是滥用了data 参数。在传递data 的地方,xyhue 将被视为对象,使用其__getitem__ 方法来索引data 中传递的对象。因此,例如,x='sepal_length', y='sepal_width', data=di 等价于 x=di['sepal_length'], y=di['sepal_width']

    因此,这运行:

    sns.lmplot(x='sepal_length', y='sepal_width', hue='species', data=di);
    

    你尝试做的基本上等同于x=di[di['sepal_length']], y=di[di['sepal_width']], hue=di[di['species']]

    回到关于scatterplotlmplot 之间区别的问题的第二部分:

    scatterplot 是一个Axes 级函数;它仅依赖于matplotlibAxes 对象,该对象在绘图时可以与listsnp.ndarrays 等不同的集合类型一起使用。在功能上,它或多或少与pyplot.scatter 相同,但有一些默认的花哨颜色。

    另一方面,lmplot 依赖于sns.FacetGrid(提供文档here)。 FacetGrid 是一个纯粹的 sns 对象,在构造时需要 pd.DataFrame。因此,因此,要使lmplot 工作,它必须采用pd.DataFrame

    【讨论】:

    • 谢谢。因此,如果我在进行可视化时主要只使用 pandas 数据框,我真的应该只使用 sns.FacetGrid 和其他构建在它之上的函数吗?还是没关系,随便用什么方便就好了。
    • 我认为反过来;如果您只使用pandas,那么没关系。另一方面,如果您使用存储在listsarrays 中的较低抽象级别的数据,那么要考虑使用哪些图/库。
    猜你喜欢
    • 2020-03-07
    • 2020-11-09
    • 1970-01-01
    • 2020-12-04
    • 2019-09-26
    • 2017-05-09
    • 1970-01-01
    • 2020-10-10
    • 2020-06-06
    相关资源
    最近更新 更多