1

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. enter image description here Thank you

  • Welcome to Stack Overflow! Please take a moment to read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask). You need to provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) that includes a toy dataset (refer to [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples)) – Diziet Asahi Oct 12 '20 at 10:36
  • 1
    "But x-axis is filled with a lot of data that is not readable" do you mean that there is missing data and you are trying to filter it? Or are you just trying to reduce the number of labels displayed on the x axis? – chris Oct 12 '20 at 15:25

1 Answers1

1

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()

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32