matplotlib 出现折线图连线不按顺序怎么办?

img


img


图上显示的,都在乱连。绘图的数据是用pandas从表格里筛选出来的。sort_values,试了一下重新进行索引排序好像也没用,不知道怎么处理。

你好,pandas数据进行sort,你只需要对x进行sort,y不需要的

import  pandas as pd
from matplotlib import pyplot as plt
d = {'x': [3, -1, 2, -2, 5], 'y': [2, 5, 2, 4, 3]}
df = pd.DataFrame(data=d)
plt.figure(1)
plt.plot(d['x'], d['y'],'r--')
df = df.sort_values(by='x', ascending=True)
plt.plot(df['x'], df['y'],'b-.')
plt.legend(['before sort','after sort'])
plt.show()

img