繁体   English   中英

在 matplotlib 轴范围内添加 x=y(45 度)线

[英]Add x=y (45 degree) line within matplotlib axis limits

我有一个具有不同 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())

一、幼稚的尝试

改进的尝试有效,但在代码方面非常丑陋:

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

在此处输入图片说明

有更好的方法吗? 我在 Matplotlib 1.3.1版上的 Spyder 2.2.5使用 IPython 1.2.1版, mpl.get_backend()返回:

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

在 matplotlib <= 3.2

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

在 matplotlib >= 3.3

matplotlib 3.3 添加了函数ax.axline ,它可以做得更好,并且如果轴限制改变仍然有效:

ax.axline([0, 0], [1, 1])

如果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)

当然,您可以调整限制。

另一种方法。

xpoints = ypoints = plt.xlim()
plt.plot(xpoints, ypoints, linestyle='--', color='k', lw=3, scalex=False, scaley=False)

来源

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM