我正在嘗試制作以下散點圖:

對于 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(),然后傳遞以逗號分隔的軸限制值?
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/418143.html
標籤:
