【问题标题】:Using seaborn, how can I draw a line of my choice across my scatterplot?使用 seaborn,我如何在散点图上画一条我选择的线?
【发布时间】:2016-07-08 21:14:56
【问题描述】:

我希望能够在 seaborn 中生成的图上绘制一条我的​​规范线。我选择的情节是 JointGrid,但任何散点图都可以。我怀疑 seaborn 可能不容易做到这一点?

这是绘制数据的代码(来自鸢尾花数据集的花瓣长度和花瓣宽度的数据帧):

import seaborn as sns
iris = sns.load_dataset("iris")    
grid = sns.JointGrid(iris.petal_length, iris.petal_width, space=0, size=6, ratio=50)
    grid.plot_joint(plt.scatter, color="g")

如果您从 iris 数据集中获取此图,我如何在其上画一条我选择的线?例如,一条负斜率线可能将集群分开,而正斜率可能会穿过它们。

【问题讨论】:

    标签: python matplotlib seaborn


    【解决方案1】:

    您似乎已将matplotlib.pyplot 导入为plt 以在您的代码中获取plt.scatter。您可以只使用 matplotlib 函数来绘制线条:

    import seaborn as sns
    import matplotlib.pyplot as plt
    
    iris = sns.load_dataset("iris")    
    grid = sns.JointGrid(iris.petal_length, iris.petal_width, space=0, size=6, ratio=50)
    grid.plot_joint(plt.scatter, color="g")
    plt.plot([0, 4], [1.5, 0], linewidth=2)
    

    【讨论】:

    • 有没有办法不为线的每个点物理放置数字?我的意思是,如果我想要 2 中的垂直线,我该如何使用 seaborn?
    • 您可以使用axvline 表示跨越整个轴的垂直线。
    【解决方案2】:

    通过在 seaborn 中创建 JointGrid,您已经创建了三个轴,主轴 ax_joint 和两个边缘轴。

    要在关节轴上绘制其他内容,我们可以使用grid.ax_joint 访问关节网格,然后在此处创建绘图对象,就像使用任何其他matplotlib Axes 对象一样。

    例如:

    import seaborn as sns
    import matplotlib.pyplot as plt
    
    iris = sns.load_dataset("iris")    
    grid = sns.JointGrid(iris.petal_length, iris.petal_width, space=0, size=6, ratio=50)
    
    # Create your scatter plot
    grid.plot_joint(plt.scatter, color="g")
    
    # Create your line plot.
    grid.ax_joint.plot([0,4], [1.5,0], 'b-', linewidth = 2)
    

    顺便说一句,您还可以以类似的方式访问JointGrid 的边缘轴:

    grid.ax_marg_x.plot(...)
    grid.ax_marg_y.plot(...)
    

    【讨论】:

      猜你喜欢
      • 2021-08-03
      • 2021-05-16
      • 1970-01-01
      • 2018-03-17
      • 2019-09-26
      • 1970-01-01
      • 2012-10-10
      • 2020-08-02
      • 1970-01-01
      相关资源
      最近更新 更多