Search code examples
pythonpandasdataframeplotstock

Axis's Plot Show Wrong Output


I have this code:

import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set()
import yfinance as yf
df = yf.download('AAPL',
                 start='2001-01-01',
                 end='2005-12-31',
                 progress=False)
df.head()
df = df.reset_index()
df['Date'] = pd.to_datetime(df.Date, format='%Y%m%d')
df.dropna(how='any', inplace=True)
# Plot the returns
plt.figure(figsize=(10,6))
plt.grid(True)
plt.xlabel('Dates')
plt.ylabel('Prices')
plt.plot(df['Close'])
plt.title('Close Price', fontsize=16)
plt.show()

The output of the close price plot is enter image description here

We can see that the dates and price didn't show correct output. I have checked the type of dataframe's date.

df.info()

The results is enter image description here

I have tried some ways but it didn't work. How to solve this problem?


Solution

  • Don't reset the index. The index Dates is already a datetime.

    import pandas as pd
    import matplotlib.pyplot as plt
    %matplotlib inline
    import seaborn as sns
    sns.set()
    import yfinance as yf
    df = yf.download('AAPL',
                     start='2001-01-01',
                     end='2005-12-31',
                     progress=False)
    # df.head()
    # df = df.reset_index()  # <- DON'T DO THAT
    # df['Date'] = pd.to_datetime(df.Date, format='%Y%m%d')  # <- DON'T DO THAT
    # df.dropna(how='any', inplace=True)
    # Plot the returns
    plt.figure(figsize=(10,6))
    plt.grid(True)
    plt.xlabel('Dates')
    plt.ylabel('Prices')
    plt.plot(df['Close'])
    plt.title('Close Price', fontsize=16)
    plt.show()
    

    enter image description here

    To modify the date axis, read Date tick labels from matplotlib documentation.