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

15

我正在使用Seaborn的jointplot来制作散点图,但似乎无法得到一个简单的对角线...我得到了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个回答

29
错误信息是一个有用的提示: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://dev59.com/m2Qo5IYBdhLWcg3wfPQa

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

一个jointplot显示了一个“山”的密度视图,X和Y轴的投影分别绘制在上方和右侧。红色线条是x=y的直线。

我在解释器中弄明白了这个问题:dir(g),然后 g.plot?g.plot_joint? - 这些都是特定于 jointplot 的绘图函数 - 还有什么?- 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()

之前的图表中,又加上了两条线,一条是中心图表的45度对角线,另一条是x=y。同时,(0,0)和(2,2)作为点被绘制以验证x=y。


我尝试几乎照字面做,但这行代码不会显示。在2019年,我还需要做其他事情才能使其工作吗? - Sledge
你的jointplot没问题,但是额外的线条不会显示?我在ipython中重新运行了几次,它可以工作(只需更新一个参数名称)。也许我们需要比较库/语言版本号。或者你有收到任何错误信息吗? - cphlewis
这是因为用于绘制对角线的最后一个代码块是错误的。从这个SO答案中,你可能更愿意使用:g.ax_joint.plot([0, 1], [0, 1], ':k', transform=g.ax_joint.transAxes) - H4dr1en

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接