绘制 45 度参考线并使 x 和 y 轴等距

drawing a 45 degrees reference line as well as making x and y axis equal range

我正在尝试绘制以下散点图:

对于具有 X 轴和 Y 轴相等范围并在散点图上覆盖 45 度参考线的对象。 我有这段代码,但产生的情节出乎我的意料。我该如何解决?

fig = plt.figure()
ax = fig.add_subplot(111)
#ax.set_aspect('equal', adjustable='box')

plt.scatter(actuals.cpu(), predictions.cpu(), cmap='viridis')
plt.xlabel('Ground Truth')
plt.ylabel('Predictions')
plt.axis('equal')
xpoints = ypoints = plt.xlim()
plt.plot(xpoints, ypoints, linestyle='--', color='k', lw=3, scalex=False, scaley=False)
plt.savefig('predictions_actuals_scatterplot.png')

这是我的 Python 和 matplotlib 版本:

$ python
Python 3.8.10 (default, Nov 26 2021, 20:14:08)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>> matplotlib.__version__
'3.5.1'

如果我只使用以下代码,虽然原点与 45 度线相交,但仍然不是我要找的。

fig = plt.figure()
ax = fig.add_subplot(111)
plt.scatter(actuals.cpu(), predictions.cpu(), cmap='viridis')
plt.xlabel('Ground Truth')
plt.ylabel('Predictions')
xpoints = ypoints = plt.xlim()
plt.plot(xpoints, ypoints, linestyle='--', color='k', lw=3, scalex=False, scaley=False)
plt.savefig('predictions_actuals_scatterplot.png')

您是否尝试过使用 plt.xticks()plt.yticks(),然后传递以逗号分隔的轴限制值?

这是你想要的吗?

import numpy as np
import matplotlib.pyplot as plt

# Generate random data.

x = np.random.random(120) * 0.21 + 0.24
y = np.random.random(120) * 1.4 - 0.2
ticks = np.arange( -0.2, 1.2, step=0.2 )

plt.scatter(x, y, cmap='viridis')
plt.xticks( ticks )
plt.yticks( ticks )
plt.plot( [-.2,1.2], [-.2,1.2], linestyle='--', color='k' )
plt.show()

输出:

问题是 plt.axis('equal') 请求在渲染图形时应用,即 after 你调用 plt.xlim()。我建议的解决方案如下,它同时使用 plt.xlim() 和 plt.ylim()。这样就不用事先知道输入数据的范围了。

import matplotlib.pyplot as plt
import numpy as np

rng = np.array([0.2, 1.5])
offset = np.array([0.25, -0.2])

xy = np.random.rand(30, 2) * rng + offset

plt.scatter(xy[:, 0], xy[:, 1], label="points")
plt.axis("equal")

left, right = plt.xlim()
bottom, top = plt.ylim()
axlim = (min(bottom, left), max(top, right))

# you can see the problem here: you've requested
# axes equal, but that has not yet been applied
# to the axes.
print(f"bottom={bottom}, top={top}, left={left}, right={right}")
print(f"Axis limits: {axlim}")

# better solution
xpoints2 = ypoints2 = np.linspace(axlim[0], axlim[1])
plt.plot(xpoints2, ypoints2, color="m", label="xlim and ylim")

# equivalent to the non-working solution
xpoints = ypoints = np.linspace(left, right)
plt.plot(xpoints, ypoints, color="g", label="xlim")

print(f"{left} {right}")
plt.grid()
plt.legend()
plt.show()

示例输出: