Search code examples
pythonmatplotlibscatter-plotaxisfigure

matplotlib axis values are not sorted


I'm using plt.scatter with a set of values, and this is the output I'm getting:

Output plot

Why am I getting these messy axis, both in the x and in the y? Why are they disordered? I would expect to have an axis starting from 0 and finishing in infinite, and not increasing and decreasing.

This is my code in case you need it:

lines = []
XsR = []
YsR = []
XsL = []
YsL = []
with open('tracking_test.txt') as f:
    lines = f.readlines()
for i in range (len(lines)):
    lines[i] = re.sub(r"[()]", " ", lines[i])
    lines[i] = lines[i].split(',')
    
    if i%2 == 0:
        XsR.append(lines[i][0])
        YsR.append(lines[i][1])
        
    else:
        XsL.append(lines[i][0])
        YsL.append(lines[i][1])   


x = np.array(XsR)
y = np.array(YsR)
plt.scatter(x, y)


x = np.array(XsL)
y = np.array(YsL)
plt.scatter(x, y)

yabs_max = abs(max(ax.get_ylim(), key=abs))
ax.set_ylim(ymin=-yabs_max, ymax=yabs_max)

plt.axhline(y=0.0, color='b', linestyle='-')
plt.axvline(x=0.0, color = 'b', linestyle = '-')

fig = matplotlib.pyplot.gcf()
fig.set_size_inches(12, 9)

plt.show()

The file contains the following:

(140.7, 217.0, 0.0)
(-230.6, 241.4, 0.0)
(0.0, 0.0, 0.0)
(0.0, 0.0, 0.0)
(0.0, 0.0, 0.0)
(0.0, 0.0, 0.0)
(229.6, 119.5, 0.0)
(0.0, 0.0, 0.0)
(232.0, 120.5, 0.0)
(0.0, 0.0, 0.0)
(241.7, 113.7, 0.0)
(-90.6, 172.4, 0.0)
(189.1, 143.0, 0.0)
(-150.3, 145.2, 0.0)
(189.1, 143.0, 0.0)
(-124.7, 182.6, 0.0)
(32.6, 15.3, 0.0)
(-39.5, 109.2, 0.0)
(32.6, 15.3, 0.0)
(-286.6, 33.6, 0.0)
(32.6, 15.3, 0.0)
(-286.6, 33.6, 0.0)
(32.6, 15.3, 0.0)
(-286.6, 33.6, 0.0)

Solution

  • The values are treated as strings. Convert them to float using:

    val = float(val)