如何更改Matplotlib折线图的X轴顺序

时间:2020-04-12 12:25:05

标签: python sorting matplotlib axis

我正在尝试可视化sklearn回归分析的结果,但无法获得按索引(月)排序的x轴。任何想法如何做到这一点?这里的代码和结果:

data = pd.DataFrame({
    'Month':['2014.01','2014.02','2014.03','2014.04','2014.05','2014.06','2014.07','2014.08','2014.09','2014.10','2014.11','2014.12'], 
    'A': ['101','102','103','104','105','106','107','108','109','110','111','112'],
    'B': ['11','12','13','14','15','16','17','18','19','20','21','22']})    

    y = data['B']
    x = data[['A']]
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1)
    linear = LinearRegression().fit(x_train,y_train)
    predicted_price = linear.predict(x_test)
    predicted_price = pd.DataFrame(predicted_price, index = y_test.index, columns = ['Forecast'])
    predicted_price.plot(figsize = (20,5))
    y_test.plot(figsize = (20,5))
    plt.show()

x-axis not sorted by Month

谢谢!

1 个答案:

答案 0 :(得分:0)

在matplotlib中,您可以指定x,y,所以您可以这样做

plt.plot(y_test.index,y_test)
plt.show()