Home > Back-end >  How can I order dates and show only month year on the x axis in matplotlib?
How can I order dates and show only month year on the x axis in matplotlib?

Time:12-30

I would like to improve my bitcoin dataset but I found that the date is not sorted in the right way and want to show only the month and year. How can I do it?

data = Bitcoin_Historical['Price']
Date1 = Bitcoin_Historical['Date']
train1 = Bitcoin_Historical[['Date','Price']]
#Setting the Date as Index
train2 = train1.set_index('Date')
train2.sort_index(inplace=True)
cols = ['Price']
train2 = train2[cols].apply(lambda x: pd.to_numeric(x.astype(str)
                     .str.replace(',',''), errors='coerce'))
print (type(train2))
print (train2.head())

plt.figure(figsize=(15, 5))
plt.plot(train2)
plt.xlabel('Date', fontsize=12)
plt.xlim(0,20)
plt.ylabel('Price', fontsize=12)
plt.title("Closing price distribution of bitcoin", fontsize=15)
plt.gcf().autofmt_xdate()
plt.show()

The result shows picture below:

result image

It's not ordered and shows all dates. I would like to order by month year and show only the month name year. How can that be done?

Example of Data:

result image

Thank you

CodePudding user response:

Try to cast your "Date" column into datetime, check if it does the trick:

train1.Date = pd.to_datetime(train1.Date)
train2 = train1.set_index('Date')

CodePudding user response:

I've made the following edits to your code:

  • converted the column Date column as datetime type
  • cleaned up the Price column and converting to float
  • removed the line plt.xlim(0,20) which is causing the output to display 1970
  • used alternative way to plot, so that the x-axis can be formatted to get monthly tick marks, more info enter image description here

  • Related