Search code examples
python-3.xdatematplotlibaxis

How can write every date in x axis?


Get stock aaa via web api:

import requests,json,time
import pandas as pd
from pandas import json_normalize
ticker = 'aaa'
start_date='2020-01-01'
end_date='2023-05-10'
fd = int(time.mktime(time.strptime(start_date, "%Y-%m-%d")))
td = int(time.mktime(time.strptime(end_date, "%Y-%m-%d")))
data = requests.get('https://apipubaws.tcbs.com.vn/stock-insight/v1/stock/bars-long-term?ticker={}&type=stock&resolution=D&from={}&to={}'.format(ticker, fd, td)).json()
df = json_normalize(data['data'])
df['tradingDate'] = pd.to_datetime(df.tradingDate.str.split("T", expand=True)[0])
df.columns = ['open', 'high', 'low', 'close', 'volume', 'date']

Prepare x,y data for plotting:

x = df['date'][0:30]
y = df['close'][0:30]

Draw the graph:

plt.plot(x,y)
plt.xticks(rotation=90)
plt.show()

There are 30 dates in the raw data (x,y),plt.show() only draw part of date,how can draw all the 30 dates in x axis?

>>> min(x)
Timestamp('2020-01-02 00:00:00')
>>> max(x)
Timestamp('2020-02-19 00:00:00')
>>> len(x)
30

I want to write every date from 2020-01-02 till 2020-02-19 ,30 dates shown on the x axis.


Solution

  • If you want every calendar date to be shown, you can add these lines at the bottom. This will show each and every calendar date (50 entries)...

    import matplotlib.dates as mdates
    from matplotlib import dates
    plt.gca().xaxis.set_major_locator(dates.DayLocator(interval=1))   #to get a tick every day
    plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%Y'))     #optional formatting 
    plt.show()
    

    enter image description here

    However, if you want to ONLY see the dates for which you have data in x, you need to add this line before plt.show() along with the code above. This will show the 30 entries....

    plt.gca().set_xticks(x)
    

    enter image description here