I've been searching and I've found some ways to do it but I can't seem to implement it into my code. Would be great if I can refer to the nationwide_lockdown_status_df for said country. Else, hardcoding the date would be fine as well.
Something like this
Please let me know if my question is lacking any clear pointers! I would gladly supply them if I can!
download link for file: sg_df
Links to what I have been referencing to
How do you plot a vertical line on a time series plot in Pandas?
matplotlib plot_date() add vertical line at specified date
So far, this is what I have working..
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime, date
#formating date and setting date as index
sg_df = pd.read_csv("^STI.csv")
conv = lambda x: datetime.strptime(x, "%d/%m/%Y")
sg_df["Date"] = sg_df["Date"].apply(conv)
sg_df.sort_values("Date", inplace = True)
sg_df.set_index("Date", inplace = True)
# country lockdown status
today = date.today()
nationwide_lockdown_status = [{"Country": "Singapore", "Lockdown Start": "2020/04/07", "Lockdown End": "2020/06/01"},
{"Country": "United Kingdom", "Lockdown Start": "2020/03/23", "Lockdown End": "NA"}]
# write to dataframe
nationwide_lockdown_status_df = pd.DataFrame(nationwide_lockdown_status)
nationwide_lockdown_status_df = nationwide_lockdown_status_df[["Country", "Lockdown Start", "Lockdown End"]]
# define figure
fig = plt.figure()
# define axis
ax1 = plt.subplot2grid((1,1), (0,0))
# define data (x, y, data, label for legend, and color)
ax1.plot(sg_df.index, "Adj Close", data = sg_df, label='Singapore', color = "c")
# set x-axis values to 45 degree angle
for label in ax1.xaxis.get_ticklabels():
label.set_rotation(45)
ax1.grid(True, color = "k", linestyle = "-", linewidth = 0.3)
plt.xlabel("Year")
# label y-axis as "Adjusted Closing Value ($)"
plt.ylabel("Adjusted Closing Value ($)")
# create legend and put legend outside of chart
plt.gca().legend(loc='center left', bbox_to_anchor=(1, 0.5), title = "Country Index")
# Title for chart
plt.title("Countries index by Year")
plt.show();
Edit
I have since found a temporary solution for this
for x in nationwide_lockdown_status:
country = x["Country"]
lockdownStartDate = x["Lockdown Start"]
lockdownEndDate = x["Lockdown End"]
if ax1:
country1 = "Singapore"
if country1 == country:
plt.axvline(pd.Timestamp(lockdownStartDate), color = "g", alpha = 0.5)
plt.axvline(pd.Timestamp(lockdownEndDate), color = "r", alpha = 0.5)