我正在尝试制作以下散点图:
对于 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')
uj5u.com热心网友回复:
这是你想要的吗?
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()
输出:
uj5u.com热心网友回复:
问题是在渲染图形时应用了 plt.axis('equal') 请求,这是在您呼叫 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()
示例输出:
uj5u.com热心网友回复:
您是否尝试过使用plt.xticks()
and plt.yticks()
,然后传递以逗号分隔的轴限制值?
0 评论