0

I am trying to visualize the outcome of a sklearn regression analysis, but I cannot get the x-axis sorted by the index (Month). Any ideas how to do this? Here the code and the outcome:

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

Thanks!

  • Since you seem to be new to Stack Overflow, you should read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Sheldore Apr 12 '20 at 12:56
  • Fair enough, I updated the code. I believe the issue happens because I am using random train/test samples. If you have any idea how to sort that x-axis, please let me know. Cheers! – CuriousDucky Apr 12 '20 at 13:26
  • @CuriousDucky. Well, people can't answer your question without having a good idea of how your data look like. For example, creating a simple data frame from code (instead from a file) and which has the same problem as your question. Something like `df = pd.DataFrame({'A': ['2018.10', ...], 'B': [....]})`. – JohanC Apr 12 '20 at 15:36
  • Thank you! Sample data included. – CuriousDucky Apr 12 '20 at 16:58
  • Does this answer your question? [Change Order on X-Axis for Matplotlib chart](https://stackoverflow.com/questions/47255746/change-order-on-x-axis-for-matplotlib-chart) – foglerit Apr 12 '20 at 17:19
  • This solution first specifies the order. I do not want to do that as there are 200+ months in my full dataset. – CuriousDucky Apr 12 '20 at 17:31

1 Answers1

0

From matplotlib you can specify x,y , so you could do

plt.plot(y_test.index,y_test)
plt.show()
jeremy_rutman
  • 3,552
  • 4
  • 28
  • 47