Python 使用 seaborn,如何在散点图上画一条我选择的线?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36146684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:28:48  来源:igfitidea点击:

Using seaborn, how can I draw a line of my choice across my scatterplot?

pythonmatplotlibseaborn

提问by user391339

I want to be able to draw a line of my specification across a plot generated in seaborn. The plot I chose was JointGrid, but any scatterplot will do. I suspect that seaborn maybe doesn't make it easy to do this?

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

Here is the code plotting the data (dataframes from the Iris dataset of petal length and petal width):

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

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

enter image description here

在此处输入图片说明

If you take this graph from the iris dataset, how can I draw a line of my choice across it? For example, a line of negative slope might separate the clusters, and positive slope might run across them.

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

回答by chthonicdaemon

It appears that you have imported matplotlib.pyplotas pltto obtain plt.scatterin your code. You can just use the matplotlib functions to plot the line:

看来您已在代码中导入matplotlib.pyplotasplt以获取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)

enter image description here

在此处输入图片说明

回答by tmdavison

By creating a JointGridin seaborn, you have created three axes, the main ax_joint, and the two marginal axes.

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

To plot something else on the joint axes, we can access the joint grid using grid.ax_joint, and then create plot objects on there as you would with any other matplotlibAxesobject.

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

For example:

例如:

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)

As an aside, you can also access the marginal axes of a JointGridin a similar way:

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

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