这个错误是一个有用的提示:一个 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://stackoverflow.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()