matplotlib 轴值未排序

matplotlib axis values are not sorted

我正在使用 plt.scatter 和一组值,这是我得到的输出:

为什么我在 x 轴和 y 轴上都得到这些凌乱的轴?他们为什么会乱?我希望有一个轴从 0 开始并无限结束,而不是增加和减少。

这是我的代码,以备不时之需:

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

文件包含以下内容:

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

这些值被视为字符串。使用以下方法将它们转换为浮点数:

val = float(val)

使用现有代码

  • 在创建数组时指定 dtype 是使用现有代码的最佳选择。
  • 鉴于 xy 是 numpy 数组(例如 x = np.array(['1', '2', '3'])
    • x.astype(float) 也可以转换类型,但最适用于可以访问数组但不能创建数组的步骤。
    • float(x) 将导致 TypeError
# convert the lists to arrays and set the dtype
XsR = np.array(XsR, dtype=float)
YsR = np.array(YsR, dtype=float)
XsL = np.array(XsL, dtype=float)
YsL = np.array(YsL, dtype=float)

fig, ax = plt.subplots(figsize=(12, 9))

ax.scatter(XsR, YsR)
ax.scatter(XsL, YsL)

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

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

使用pandas

  • 鉴于您的数据,最简洁的解决方案是使用 pandas 来读取带有 .read_csv() 的数据,但将分隔符设置为 , 以外的其他内容。
    • 这使得 pandas 从文件中读取 tuple 到单个列中
  • 使用ast.literal_eval将字符串文字列转换为文字,在本例中,tuple of floats
  • tuple 分成单独的列,然后用 pandas.DataFrame.plot 绘制 DataFrame。
  • 这将代码从 29 行减少到仅 11 行。
  • 使用 pandas v1.2.4matplotlib v3.3.4
    • pandas imports matplotlib 作为依赖,所以使用下面的代码,如图,不需要单独import matplotlib
import pandas as pd
from ast import literal_eval

# load the data from your file; as shown in the OP, there's no header, so the column will be named 0
# convert the column with ast.literal_eval
df = pd.read_csv('test.csv', sep=';', header=None, converters={0: literal_eval})

# display(df.head(2))
                      0
0   (140.7, 217.0, 0.0)
1  (-230.6, 241.4, 0.0)

# split the column into separate columns
df[['x', 'y', 'z']] = pd.DataFrame(df[0].tolist(), index= df.index)

# display(df.head(2))
                      0      x      y    z
0   (140.7, 217.0, 0.0)  140.7  217.0  0.0
1  (-230.6, 241.4, 0.0) -230.6  241.4  0.0

# split the data by odd and even indices
mask = df.index % 2 == 0
df_sR = df[mask]
df_sL = df[~mask]

# plot the dataframe
ax = df_sR.plot(kind='scatter', x='x', y='y', figsize=(12, 9), c='blue')
df_sL.plot(kind='scatter', x='x', y='y', ax=ax, c='orange')

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

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