在matplotlib轴限制内添加x=y(45度)线

2024-04-25 05:39:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个x和y界限不同的图:

fig, ax = subplots(ncols=1)
ax.set_xlim([0, 10])
ax.set_ylim([5, 10])

我想在这个图中添加一条x=y线,但要保持该线在轴的限制范围内。

我第一次天真的尝试是

ax.plot(ax.get_xlim(), ax.get_xlim())

First, naive attempt

改进后的尝试可以工作,但在代码方面却非常难看:

ax.plot([max(ax.get_xlim()[0], ax.get_ylim()[0]), 
         min(ax.get_xlim()[1], ax.get_ylim()[1])],
        [max(ax.get_xlim()[0], ax.get_ylim()[0]), 
         min(ax.get_xlim()[1], ax.get_ylim()[1])])

enter image description here

有更好的办法吗? 我在Spyder中使用IPython版本1.2.1,在Matplotlib版本1.3.1上使用2.2.5,返回:

'module://IPython.kernel.zmq.pylab.backend_inline'

Tags: 代码版本getplotipythonfigaxmin
2条回答

如果0 <= X <= 10 <= Y <= 1,这对我有效:

import matplotlib.pyplot as plt

plt.scatter(X, Y)
plt.plot([0, 1], [0, 1], color = 'black', linewidth = 2)
plt.xlim(-0.05, 1.05)
plt.ylim(-0.05, 1.05)

当然,你可以调整限额。

x = np.linspace(*ax.get_xlim())
ax.plot(x, x)

相关问题 更多 >