Search code examples
pythonmatplotlibtimestampindices

plot timestamps and index in the same plot


Hi I'm trying to figure out if you can plot dates on one axis and corresponding integer indices on another axis in the same subplot with matplotlib, for example just the price with dates on one axes and price and corresponding integers indices (to the dates, in the example idx = np.arange(len(aapl))) . Here is an example of a stock signal.

import yfinance as yf
import matplotlib.pyplot as plt

# Download Apple's stock price data
aapl = yf.download("AAPL", start="2022-01-01", end="2023-04-30")

# Plot the adjusted close price
plt.plot(aapl['Adj Close'])

# Set x-axis label, y-axis label, and title
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('AAPL Stock Price')

# Display the plot
plt.show() 

Solution

  • You can do that by setting up a twin axis (ax2) with ax2=ax.twiny() (doc here). Once the new axis is created you can place the labels you want with ax2.set_xticks() (see doc here).

    Here is the full code applied to your example:

    import yfinance as yf
    import matplotlib.pyplot as plt
    import numpy as np
    
    # Download Apple's stock price data
    aapl = yf.download("AAPL", start="2022-01-01", end="2023-04-30")
    
    
    fig,ax=plt.subplots()
    # Plot the adjusted close price
    plt.plot(aapl['Adj Close'])
    
    # Set x-axis label, y-axis label, and title
    ax.set_xlabel('Date')
    ax.set_ylabel('Price')
    ax.set_title('AAPL Stock Price')
    
    ax2=ax.twiny()
    N_pts=len(aapl['Adj Close'])
    tcks=np.linspace(0,1,N_pts) #tick positions
    labs=np.arange(N_pts) #tick labels
    freq=20 #tick frequency
    
    ax2.set_xticks(tcks[::freq],labs[::freq])#set up ticks
    ax2.set_xlabel('index') #label the new axis
    # Display the plot
    plt.tight_layout()
    plt.show() 
    

    enter image description here