About matplotlib x-axis date format setting Hello everyone: I am learning to write a crawler program in python Stock information obtained through the yfinance package Use matplotlib to draw line graphs But the date format of the axis drawn by matplotlib Is e.g. 03 Nov 2021, not the matplotlib date format I want
I hope that the date format of the x-axis drawn by matplotlib can be changed Change to the format of yyyy-mm-dd, I hope everyone can help
my code:
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.dates import DateFormatter as mdates
startday = '2021-11-03'
endday = '2021-11-12'
ticker_list = ['2303.TW','2610.TW','2618.TW']
data = pd.DataFrame(columns=ticker_list)
for ticker in ticker_list:
data[ticker] = yf.download(ticker, startday,endday)['Adj Close'] #Get the closing price of the stock market on that day
ans=data.head()
#Start drawing
data.plot(figsize=(8,12))
plt.legend()
plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei']
plt.rcParams['axes.unicode_minus'] = False
plt.title("Line chart change of 7-day closing price of stock market", fontsize=16)
plt.ylabel('closing price', fontsize=14)
plt.xlabel('Day', fontsize=14)
plt.grid(which="major", color='k', linestyle='-.', linewidth=0.5)
plt.show()
print(ans)
CodePudding user response:
You need both a locator and formatter. Reference: https://matplotlib.org/stable/gallery/text_labels_and_annotations/date.html And the way you imported mdates
isn't how it's usually done, so I've adjusted that too.
# ... other imports
import matplotlib.dates as mdates
startday = '2021-11-03'
endday = '2021-11-12'
ticker_list = ['2303.TW','2610.TW','2618.TW']
data = pd.DataFrame(columns=ticker_list)
for ticker in ticker_list:
data[ticker] = yf.download(ticker, startday,endday)['Adj Close']
ans=data.head()
data.plot(figsize=(8,12))
plt.legend()
plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei']
plt.rcParams['axes.unicode_minus'] = False
plt.title("Line chart change of 7-day closing price of stock market",
fontsize=16)
plt.ylabel('closing price', fontsize=14)
plt.xlabel('Day', fontsize=14)
plt.grid(which="major", color='k', linestyle='-.', linewidth=0.5)
fmt_day = mdates.DayLocator() # provides a list of days
plt.gca().xaxis.set_major_locator(fmt_day)
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
plt.show()