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
Using seaborn, how can I draw a line of my choice across my scatterplot?
提问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")
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.pyplot
as plt
to obtain plt.scatter
in your code. You can just use the matplotlib functions to plot the line:
看来您已在代码中导入matplotlib.pyplot
asplt
以获取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)
回答by tmdavison
By creating a JointGrid
in 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 matplotlib
Axes
object.
要在关节轴上绘制其他内容,我们可以使用 访问关节网格grid.ax_joint
,然后像使用任何其他matplotlib
Axes
对象一样在那里创建绘图对象。
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 JointGrid
in a similar way:
JointGrid
顺便说一句,您还可以以类似的方式访问 a 的边缘轴:
grid.ax_marg_x.plot(...)
grid.ax_marg_y.plot(...)