在 Seaborn Jointplot 上绘制对角线(相等线)

Posted

技术标签:

【中文标题】在 Seaborn Jointplot 上绘制对角线(相等线)【英文标题】:Drawing Diagonal line (line of equality) on Seaborn Jointplot 【发布时间】:2015-10-02 04:48:48 【问题描述】:

我正在使用 seaborn 联合图来绘制散点图,但我似乎无法得到一条简单的对角线...我得到了 AttributeError: 'JointGrid' object has no attribute 'get_xlim'。有人知道使用 Seaborn 的解决方法吗?

这是我的代码(标题也没有显示!给出了什么):

ax = sns.jointplot(x="Av Tomato-meter", y="Av Audience Score", data=director_combined_ratings, stat_func = None, 
                   size = 8, xlim=(0,100), ylim=(0,100))

ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c=".3") #this is the error line.

ax.title = "Average Tomato-meter vs Audience Score for Directors with over 10 Movies"

提前谢谢大家。

【问题讨论】:

【参考方案1】:

这个错误是一个有用的提示:一个 JointGrid 组织了几个子图,你必须找到特定的ax 来绘制。 :

import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib.pyplot import show
sns.set_style('darkgrid')

# Generate a random correlated bivariate dataset
# https://***.com/questions/16024677/generate-correlated-data-in-python-3-3

rs = np.random.RandomState(5)
mean = [0, 0]
cov = [[2, .1],
       [.5, 3]]  # make it asymmetric as a better test of x=y line
y = np.random.multivariate_normal(mean, cov, 500, tol=1e-4)

# Show the joint distribution using kernel density estimation
g = sns.jointplot(x=y[:,0], y=y[:,1],
                  kind="kde",
                  fill="true", height=5, space=0, levels=7)

# Draw a line of x=y 
x0, x1 = g.ax_joint.get_xlim()
y0, y1 = g.ax_joint.get_ylim()
lims = [max(x0, y0), min(x1, y1)]
g.ax_joint.plot(lims, lims, '-r')
show()

我在解释器中发现了这一点:dir(g),然后是g.plot?g.plot_joint?——这些是特定于联合图的绘图函数——还有什么? --dir(g.ax_joint);啊哈,还有set_ylim等。

对角线是 x=y 线,但请注意,它不是中心图像素的 45 度对角线。 seaborn jointplot 函数总是绘制一个正方形的中心图。当数据不对称时,绘图的 X 和 Y 轴将更改以适合正方形。变量lims 将显示的边缘保存在数据坐标中。

有一条评论建议绘制的对角线始终是显示的对角线,但它不是数据的相等线。以下是要添加的几行代码来测试并找出您想要的:

# This will always go from corner to corner of the displayed plot
g.ax_joint.plot([0,1], [0,1], ':y', transform=g.ax_joint.transAxes)

# This is the x=y line using transforms
g.ax_joint.plot(lims, lims, 'w', linestyle='dashdot', transform=g.ax_joint.transData)

# This is a simple way of checking which is x=y
g.ax_joint.scatter(x=[0, 2],y=[0,2], s=30,c= 'w',marker='o')
show()

【讨论】:

我正在尝试几乎逐字逐句地执行此操作,但该行不会显示。为了在 2019 年完成这项工作,我还需要做什么? 你的jointplot没问题,但是额外的行不会显示?我只是在 ipython 中重新运行了几次,它起作用了(更新了一个参数名称)。我们可能需要比较库/语言版本号。还是您收到任何错误消息? 那是因为最后一个用于绘制对角线的代码块是错误的。来自this SO answer,您可能更愿意使用:g.ax_joint.plot([0, 1], [0, 1], ':k', transform=g.ax_joint.transAxes)

以上是关于在 Seaborn Jointplot 上绘制对角线(相等线)的主要内容,如果未能解决你的问题,请参考以下文章

如何绘制非方形 Seaborn jointplot 或 JointGrid

(数据科学学习手札62)详解seaborn中的kdeplotrugplotdistplot与jointplot

seaborn使用jointplot函数为散点图添加边缘图为散点图添加边缘直方图(Marginal Plot in Python with Seaborn jointplot)

使用 seaborn 的 Jointplot 多索引列

Seaborn:我只想要一个对数刻度

seaborn使用jointplot函数为散点图添加边缘图添加回归线为边缘直方图添加密度曲线(Add Regression Line to Marginal Plot)