I am plotting the stock price of a particular company of 10 years data. But x-axis is filled with a lot of data that is not readable. I tried many solutions to reduce the x-axis frequency. I don't want to floaded the x-axis rather I would be happy to show only the ticks on semi-annual basis. Below is my code. Please help me in getting the desired plot.
plt.figure(figsize=(25,5))
plt.plot(amd_df['date'][:train_seq],amd_df['close'][:train_seq],color='b',label = 'Train Data')
plt.plot(amd_df['date'][train_seq:],amd_df['close'][train_seq:],color='r',label = 'Test Data')
plt.title('AMD Stock Price')
plt.xlabel('Date')
plt.ylabel('Stock Price')
plt.xticks( rotation=25 )
plt.legend()
plt.show()
We have about 2683 data points in this plot. Please see below. Thank you
No data was provided, so we responded by creating sample data with random numbers. The point is to set MOnthLocator(interval=6)
and set it to Dateformatter()
. See the official reference .
import pandas as pd
import numpy as np
date_rng = pd.date_range('2010-01-01','2020-01-01', freq='B')
val = np.random.randint(0,100,(2609))
amd_df = pd.DataFrame({'date':date_rng,'close':val})
amd_df['date'] = pd.to_datetime(amd_df['date'])
train_seq = 2500
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
fig = plt.figure(figsize=(25,5))
ax = fig.add_subplot(111)
ax.plot(amd_df['date'][:train_seq],amd_df['close'][:train_seq],color='b',label = 'Train Data')
ax.plot(amd_df['date'][train_seq:],amd_df['close'][train_seq:],color='r',label = 'Test Data')
ax.set_title('AMD Stock Price')
ax.set_xlabel('Date')
ax.set_ylabel('Stock Price')
months = mdates.MonthLocator(interval=6)
months_fmt = mdates.DateFormatter('%y-%m')
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(months_fmt)
ax.legend()
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.