<p>从图的左下角到右上角画一条对角线可以通过以下方法完成</p>
<p><code>ax.plot([0, 1], [0, 1], transform=ax.transAxes)</code></p>
<p>使用<code>transform=ax.transAxes</code>,提供的<code>x</code>和<code>y</code>坐标被解释为<em>轴</em>坐标,而不是<em>数据</em>坐标。</p>
<p>正如@fqq所指出的,当你的<code>x</code>和<code>y</code>限制相等时,这只是身份线。要绘制线<code>y=x</code>,使其始终延伸到绘图的极限,可以使用类似于@Ffisegydd所给出的方法,并可以编写为以下函数。</p>
<pre><code>def add_identity(axes, *line_args, **line_kwargs):
identity, = axes.plot([], [], *line_args, **line_kwargs)
def callback(axes):
low_x, high_x = axes.get_xlim()
low_y, high_y = axes.get_ylim()
low = max(low_x, low_y)
high = min(high_x, high_y)
identity.set_data([low, high], [low, high])
callback(axes)
axes.callbacks.connect('xlim_changed', callback)
axes.callbacks.connect('ylim_changed', callback)
return axes
</code></pre>
<p>示例用法:</p>
<pre><code>import 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")
add_identity(ax, color='r', ls='--')
plt.show()
</code></pre>