从屏幕左下角到右上角绘制对角线非常简单,您只需使用ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c=".3")。方法ax.get_xlim()将简单地返回x轴的当前值(对于y轴也是如此)。
但是,如果您希望能够使用图形进行缩放,则会变得稍微复杂一些,因为您绘制的对角线不会更改为与新的xlims和ylims匹配。
在这种情况下,可以使用回调来检查xlims(或ylims)何时发生了更改,并相应地更改对角线中的数据(如下所示)。我在this example中找到了回调的方法。还可以找到更多信息hereimport numpy as np
import matplotlib.pyplot as plt
mean, cov = [0, 0], [(1, .6), (.6, 1)]
x, y = np.random.multivariate_normal(mean, cov, 100).T
y += x + 1
f, ax = plt.subplots(figsize=(6, 6))
ax.scatter(x, y, c=".3")
ax.set(xlim=(-3, 3), ylim=(-3, 3))
# Plot your initial diagonal line based on the starting
# xlims and ylims.
diag_line, = ax.plot(ax.get_xlim(), ax.get_ylim(), ls="--", c=".3")
def on_change(axes):
# Whe