I am trying to plot a data of stock close price for each day but on the x-axis, i get no labels on xtick instead of year-month format
I tried to take the “Date” and “Close Price” column in a separate dataframe and then tried plotting them.
I have dataframe similar to this
JavaScript
x
7
1
Date Close Price
2
2017-05-15 912.20
3
2017-05-16 894.70
4
2017-05-17 887.05
5
2017-05-18 871.35
6
2017-05-19 852.40
7
JavaScript
1
9
1
df_sorted.plot(x="Date", y="Close Price", figsize=(8, 5))
2
plt.title('Trend in last two years')
3
plt.ylabel('Close Price') # add y-label
4
plt.xlabel('Date') # add x-label
5
6
plt.show()
7
8
the output should have xtick in year-month format
9
Advertisement
Answer
Just covert it with pandas to_datetime()
function
JavaScript
1
8
1
df_sorted['Date'] = pd.to_datetime(df_sorted['Date'])
2
df_sorted.plot(x="Date", y="Close Price", figsize=(8, 5))
3
plt.title('Trend in last two years')
4
plt.ylabel('Close Price') # add y-label
5
plt.xlabel('Date') # add x-label
6
7
plt.show()
8